Hello there,
I am inserting Images during mail merge process at run time. In some cases, I also need to apply formatting to selected Images.
Below is the code snippet in MailMerge_MergeImageField handler:
private void MailMerge_MergeImageField(object sender, MergeImageFieldEventArgs e)
{
byte[] imageBytes = (e.FieldValue as byte[]);
if (imageBytes != null)
{
if (imageFormattingDictionary.Count> 0 && imageFormattingDictionary.ContainsKey(e.FieldName))
{
bool isImageInserted = false;
Image objImage = Image.FromStream(new MemoryStream((byte[]) e.FieldValue));
// Apply Image Formatting
Dictionary <string, string> imageFormatting = imageFormattingDictionary[e.FieldName];
foreach(string key in imageFormatting.Keys)
{
switch (key)
{
case "SIZE":
Bitmap objBitmap = null;
string imageSize = imageFormatting[key];
if (imageSize == "S")
{
objBitmap = new Bitmap(objImage, new Size(227, 171));
}
else if (imageSize == "N")
{
objBitmap = new Bitmap(objImage, new Size(353, 265));
}
objImage = objBitmap;
break;
case "ALIGN":
DocumentBuilder builder = new DocumentBuilder(e.Document);
builder.MoveToMergeField(e.FieldName);
Shape shape = builder.InsertImage(objImage);
isImageInserted = true;
shape.WrapType = WrapType.Square;
shape.BehindText = true;
string imageAlignment = imageFormatting[key];
if (imageAlignment == "RIGHT")
{
shape.HorizontalAlignment = HorizontalAlignment.Right;
}
else if (imageAlignment == "CENTER")
{
shape.HorizontalAlignment = HorizontalAlignment.Center;
}
else
{
shape.HorizontalAlignment = HorizontalAlignment.Left;
}
break;
}
}
if (!isImageInserted)
{
e.Image = objImage;
}
}
else
{
e.Image = Image.FromStream(new MemoryStream((byte[]) e.FieldValue));
}
}
else
{
e.Field.Remove();
}
}
I have two issues here:
- When I am iterating over imageFormatting.Keys in
foreach(string key in imageFormatting.Keys)
I want a way so that I apply all the formatting viz. SIZE and ALIGN and then finally insert image for the merge field. But, I do not know a way in case “ALIGN” where a Shape object is required to be inserted in the document before applying any wrapping style. So setting e.Image will be useless in case of ALIGN as shape is already inserted.
Please suggest if there is another work around for this that can help me to set e.Image after foreach loop.
- Wrapping Text around Image: I just want the text from only first paragraph following Image to be wrapped around. But in output, it just wraps maximum text that can be wrapped around image depending on image’s size. Please suggest if I can achieve this.
Source+Output docs are attached for your reference.
Thank you!