Last article we have shown how to create the mail merge template and merge the text value to it by using Spire.Doc. As we know that, besides the text value, we also use the mail merge feature to merge the image value too. This article will demonstrate how to merge the image value to the mail merge template in C#.
Here comes to the details of how use the mail merge to merge the image value. Firstly, please view the mail merge template and the image later will be merged to it.
Step 1: Create a new word document and load the document from the file.
Document doc = new Document(); doc.LoadFromFile("Test.docx");
Step 2: Set the value for the mail merge template by the fieldname.
var fieldNames = new string[] { "MyImage" }; var fieldValues = new string[] { "logo.png" };
Step 3: Create a method to get the image file:
void MailMerge_MergeImageField(object sender, MergeImageFieldEventArgs field) { string filePath = field.FieldValue as string; if (!string.IsNullOrEmpty(filePath)) { field.Image = Image.FromFile(filePath); } }
Step 4: Call the method MailMerge_MergeImageField() to get the image and then merge the specified value into template.
doc.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MailMerge_MergeImageField);
Step 5: Save the document to file.
doc.SaveToFile("result.docx", FileFormat.Docx);
Effective screenshot after merge the image value to the mail merge template:
Full codes:
using Spire.Doc; using Spire.Doc.Reporting; using System.Drawing; namespace MailMerge { class Program { class MailMergeImage { public MailMergeImage() { Document doc = new Document(); doc.LoadFromFile("Test.docx"); var fieldNames = new string[] { "MyImage" }; var fieldValues = new string[] { "logo.png" }; doc.MailMerge.MergeImageField += new MergeImageFieldEventHandler(MailMerge_MergeImageField); doc.MailMerge.Execute(fieldNames, fieldValues); doc.SaveToFile("result.docx", FileFormat.Docx); } void MailMerge_MergeImageField(object sender, MergeImageFieldEventArgs field) { string filePath = field.FieldValue as string; if (!string.IsNullOrEmpty(filePath)) { field.Image = Image.FromFile(filePath); } } } } }