Free Support Forum - aspose.com

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” });<o:p></o:p>

doc.Save(@“C:\Temp\out.docx”);<o:p></o:p>


private class HandleImageMergeField : IFieldMergingCallback<o:p></o:p>

{<o:p></o:p>

void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)<o:p></o:p>

{<o:p></o:p>

// Do nothing.<o:p></o:p>

}<o:p></o:p>

void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs e)<o:p></o:p>

{<o:p></o:p>

e.ImageFileName = e.FieldValue.ToString();<o:p></o:p>

}<o:p></o:p>

}<o:p></o:p>


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);<o:p></o:p>

builder.MoveToMergeField(“MyImageField”);<o:p></o:p>

builder.InsertImage(@“C:\Temp\Sample.png”, 200, 200);<o:p></o:p>

doc.Save(@“C:\Temp\out.docx”);<o:p></o:p>


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,