Images in a Merge Field

Can anyone/someone let me know if it’s possible to insert a bitmap/jpeg, etc. into a merge field? If so, can you please provide a code sample for doing so.
Thank you in advance,
Anthony

Hi Anthony,

Thanks for your inquiry. To be able to insert images at a merge field, you first need to configure merge field’s name according to the following syntax in your template document:

Image:MyFieldName

Secondly, you can simply use the following code snippet to insert images during mail merge:

// Create array with field names and array with field values
string[] names = {
    "MyFieldName"
};
object[] values = {
    File.ReadAllBytes(@"Common\test.jpg")
};
// Open template
Document doc = new Document(@"Test040\in.doc");
doc.MailMerge.FieldMergingCallback = new HandleMergeImageFieldFromBlob();
// Execute mail merge
doc.MailMerge.Execute(names, values);
// Save output document
doc.Save(@"Test040\out.doc");
private class HandleMergeImageFieldFromBlob: IFieldMergingCallback
{
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
    {}
    public void ImageFieldMerging(ImageFieldMergingArgs args)
    {
        if (args.FieldName.Equals("MyFieldName"))
        {
            DocumentBuilder builder = new DocumentBuilder(args.Document);
            builder.MoveToMergeField(args.FieldName);

            builder.InsertImage(args.FieldValue.ToString(), 200, 200);
        }
    }
}

Moreover, you can find documentation of DocumentBuilder.InsertImage method overloads here:
https://reference.aspose.com/words/net/aspose.words/documentbuilder/insertimage/

I hope, this helps.

Best regards,

Awais,
Thank you for the code. I’m testing within an ASP.NET MVC Web application and the ImageFieldMerging callback is never fired/executed. Is there an alternate means to making this code work on a Web page?
Thanks,
Anthony

Awais, just wanting to be clear that we are using ASP.NET MVC 4.0 (and NOT classic ASP OR ASP.NET Web Forms) so the solution would need to be able to work in that context.
Update, I got the signature to work by removing the property set of FieldMergingCallback and putting the code in the ImageFieldMerging method directly after the Execute call of MailMerge. In addition, I removed the field name and value from the fieldnames and fieldvalues arrays.

Hi Anthony,

It’s great you were able to find what you were looking for. Moreover, you can also use the following simple code to manually move cursor to a position just beyond the specified merge field, remove the merge field and insert image there.

Document doc = new Document(@"C:\Temp\in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);

builder.MoveToMergeField("simplefield");
builder.InsertImage(@"C:\Temp\Aspose.Words.png");

doc.Save(@"C:\Temp\out.docx");

Please let us know any time you have any further queries.

Best regards,