I have a document that I am performing MailMerge on. We also want to dynamically pull images (.jpg or .tiff) from the file system and place them in the document at specific spots on the document. The name of the file will be passed in one of the MailMerge data fields.
Hi Robert,
There
are three properties available ImageFileName, ImageStream and Image to
specify where the image must be taken from. Set only one of these
properties. Please see the following highlighted code snippet.
Document doc = new
Document(MyDir + “in.docx”);
//Your code…
//Your code...
doc.MailMerge.FieldMergingCallback = new HandleMergeImageField();
doc.MailMerge.Execute(datatable); //Pass the datatable in Execute method
doc.Save(MyDir + "Out.docx");
private class HandleMergeImageField : IFieldMergingCallback
{
void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
{
// Do nothing.
}
///
/// This is called when mail merge engine encounters Image:XXX merge field in the document.
/// You have a chance to return an Image object, file name or a stream that contains the image.
///
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
{
MemoryStream stream = (MemoryStream)e.FieldValue;
stream.Position = 0;
// Now the mail merge engine will retrieve the image from the stream.
e.ImageStream = stream;
}
}
Moreover, please visit the following documentation link for your kind reference.
Robert343:
The name of the file will be passed in one of the MailMerge data fields.
If you want to pass image file name (path of image), please use the ImageFieldMergingArgs.ImageFileName property. This property sets the file name of the image that the mail merge engine must insert into the document. Please check the following code example.
Hope this helps you. Please let us know if you have any more queries.
Document doc = new Document(MyDir + "in.docx");
doc.MailMerge.FieldMergingCallback = new MailMergeInsertImage();
doc.MailMerge.Execute(
new string[] { "MyFieldName" },
new object[] { MyDir + "image.jpg" });
doc.Save(MyDir + "Out.docx");
public class MailMergeInsertImage : IFieldMergingCallback
{
void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
{
}
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
{
e.ImageFileName = e.FieldValue.ToString();
}
}