本文将介绍如何使用Spire.Doc for Java的邮件合并功能合并图片到Word文档。
模板文档:
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 MailMergeImage {
public static void main(String[] args) throws Exception {
//创建Document实例
Document document = new Document();
//加载模板文档
document.loadFromFile("template.docx");
//合并域名称
String[] filedNames = new String[]{"image"};
//图片路径
String[] filedValues = new String[]{"logo.png"};
//调用邮件合并事件加载图片
document.getMailMerge().MergeImageField = new MergeImageFieldEventHandler() {
public void invoke(Object sender, MergeImageFieldEventArgs args) {
mailMerge_MergeImageField(sender, args);
}
};
//执行邮件合并
document.getMailMerge().execute(filedNames, filedValues);
//保存文档
document.saveToFile("MailMergeImage.docx", FileFormat.Docx_2013);
}
//创建邮件合并事件用于加载图片
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();
}
}
}
}
结果文档: