Insert image using MailMerge


I am using the MailMerge.UseNonMergeFields feature to insert text into a template. For example: {{Person.Name}} is replaced with the proper name.

Now I would also like to add images into the same document, using a similar syntax. So {{Person.Image}} would need to be replaced by an image. I also want to be be able to specify the dimensions of this image:
{{Person.Image -w 120px -h 120px}} or
{{Person.Image -w 100% -h 100%}}, where the image will fill it’s container (which can be a textbox or just the whole page).
(The syntax can be different, this is just a draft I came up with)

In the future I may also want to expand this to produce additional table rows or list items (using some kind of {{Foreach…}} syntax). But for now the images are most important.

Is this behaviour possible using
A different feature in Aspose.Words,
or do I need to write a custom template engine for this?



Thanks for your inquiry. Please insert the image field with the following syntax in your document to insert the image using mail merge. You can change the ImageName to your desired field name.
{{ Image:ImageName }}

Please implement IFieldMergingCallback interface to control how data is inserted into merge fields during a mail merge operation. Please check the following code example.

Document doc = new Document(MyDir + "in.docx");
doc.MailMerge.FieldMergingCallback = new Handle_MergeField();
doc.MailMerge.UseNonMergeFields = true;
doc.MailMerge.Execute(new string[] { "Person.Name", "ImageName" }, new object[] { "Tahir", "" });

doc.Save(MyDir + "Out.docx");

private class Handle_MergeField : IFieldMergingCallback
    /// <summary>
    /// This is called when merge field is actually merged with data in the document.
    /// </summary>
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
        //Your code

    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
        // Your code

We suggest you please read known issues about mail merge using ‘Mustache’ template syntax.


Thank you Tahir, that worked wonderfully!