Putting an image in a word document

I’m trying to make a word document with images. I specified a mail merge field by Image:PictureName.
For the corrosponding field in the dictionary I tried using a memory stream and a byte array. The image is a code generated graph with some text written over it. I tried using different image types, my preferred type is Emf because it’s a vector type.

None worked, can someone please explain how this should be done?

Adding the key, has been tested with graph being a MemoryStream or a bye array, is a working image because writing it to a file produces a correct image:

MergeData.Add("PictureName", graph);

Mergefield with field codes toggled:
{ MERGEFIELD Image:PictureName \* MERGEFORMAT }

Hi,

Thanks for your inquiry. I have attached a template Word document that contains a sample Image MERGEFIELD here for your reference. I believe you can achieve what you need after using the code suggested below:

Document doc = new Document(@"C:\Temp\ImageTemplate.docx");
doc.MailMerge.Execute(new string[]
{
    "MyImageField"
}, new object[]
{
    @"C:\temp\Sample.png"
});
doc.Save(@"C:\Temp\out.docx");

private class HandleImageMergeField: IFieldMergingCallback
{
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
    {
        // Do nothing.
    }
    void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)
    {
        e.ImageFileName = e.FieldValue.ToString();
    }
}

Alternatively, you can use DocumentBuilder object to move the cursor to a MERGEFIELD and then insert the image there by using the following code snippet:

Document doc = new Document(@"C:\Temp\ImageTemplate.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.MoveToMergeField("MyImageField");
builder.InsertImage(@"C:\Temp\Sample.png", 200, 200);
doc.Save(@"C:\Temp\out.docx");

Please let me know if I can be of any further assistance.

Best regards,

Neither of these methods worked (the second inserted the image, but at the top of the page). I ended up using placeholder images with the alternate text holding the attribute name for the image.

Hi,

It’s great you were able to find what you were looking for. Please let us know any time you have any further queries.

Best regards,