aspose word模板文件生成pdf
# aspose word模板文件生成pdf package com.example.core.mydemo; import com.alibaba.fastjson.JSON; import com.aspose.words.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.InputStream; import java.util.Map; import java.util.Objects; import java.util.regex.Pattern; public class WordUtil { public static final String PARAM_MATCH = "\\{[a-zA-Z]+\\}"; private static final Logger logger = LoggerFactory.getLogger(WordUtil.class); public static void replaceText(Map<String,String> paramMap,Document doc) throws Exception { FindReplaceOptions opt = new FindReplaceOptions(); for (Map.Entry<String, String> entry : paramMap.entrySet()) { String key = String.format("{%s}", entry.getKey()); String value = Objects.isNull(entry.getValue()) ? "" : entry.getValue(); doc.getRange().replace(key,value,opt); } int replace = doc.getRange().replace(Pattern.compile(PARAM_MATCH), "", opt); if(replace>0){ logger.error("未知参数:{}",JSON.toJSONString(paramMap)); } } public static void replaceBookMark(String bookmarkName,String newBookValue,Document doc) throws Exception { BookmarkCollection bookmarks = doc.getRange().getBookmarks(); for (Bookmark bookmark : bookmarks) { if(Objects.equals(bookmark.getName(),bookmarkName)){ bookmark.setText(newBookValue); return; } } } public static void replaceBookMarkImage(String bookmarkName, InputStream inputStream, Document doc) throws Exception { DocumentBuilder db=new DocumentBuilder(doc); db.moveToBookmark(bookmarkName); db.insertImage(inputStream,119.4,64); } } package com.example.core.mydemo; import com.aspose.words.Document; import com.aspose.words.SaveFormat; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.HashMap; import java.util.Map; public class PDFTest { public static final String PDF = ".pdf"; public static void main(String[] args) { try{ String templatePath = "E:\\contract2.docx"; Document document=new Document(new FileInputStream(templatePath)); Map paramsMap = new HashMap(); paramsMap.put("realname","刘德华"); paramsMap.put("addr","香港"); WordUtil.replaceText(paramsMap,document); String name="aaabbb"; File tempFile = File.createTempFile(name, PDF); System.out.println("文件=" + tempFile.getName()); document.save(new FileOutputStream(tempFile), SaveFormat.PDF); System.out.println("finish" + tempFile.getAbsolutePath() + "-" + tempFile.getCanonicalPath()); }catch (Exception e){ e.printStackTrace(); } } }
contract2.docx 模板文件
通知
明星 {realname} 在{addr}举行演唱会,大家来捧场啊!!
导入jar包
aspose-words-19.5jdk.jar
aspose-cells-8.5.2.jar
生成的pdf文件样式
通知
明星 刘德华 在香港举行演唱会,大家来捧场啊!!