This article demonstrates how to mail merge image in Word document in Java using Spire.Doc for Java.
The template document:
import com.spire.doc.Document; import com.spire.doc.FileFormat; import com.spire.doc.reporting.MergeImageFieldEventArgs; import com.spire.doc.reporting.MergeImageFieldEventHandler; import java.text.SimpleDateFormat; import java.util.Date; public class SimpleMailMerge { public static void main(String[] args) throws Exception { //create a Document instance Document document = new Document(); //load the template document document.loadFromFile("template - Copy.docx"); //specify the merge field name String[] filedNames = new String[]{"image"}; //specify the path of image String[] filedValues = new String[]{"logo.png"}; //invoke the mail merge event to load image document.getMailMerge().MergeImageField = new MergeImageFieldEventHandler() { public void invoke(Object sender, MergeImageFieldEventArgs args) { mailMerge_MergeImageField(sender, args); } }; //execute mail merge document.getMailMerge().execute(filedNames, filedValues); //save file document.saveToFile("MailMergeImage.docx", FileFormat.Docx_2013); } //create a mail merge event to load image private static void mailMerge_MergeImageField(Object sender, MergeImageFieldEventArgs field) { String filePath = field.getImageFileName(); if (filePath != null && !"".equals(filePath)) { try { field.setImage(filePath); } catch (Exception e) { e.printStackTrace(); } } } }
The output document: