总体思路就是: 使用word模板引擎,将占位符(格式:{{title}})替换为查询出来的数据,再将替换完成的word转换为pdfjava
doc转pdf源码: https://gitee.com/java_long/docs-to-pdf-converter.gitgit
word模板引擎: https://github.com/Sayi/poi-tl.gitgithub
pom依赖:字体
<dependency> <groupId>com.deepoove</groupId> <artifactId>poi-tl</artifactId> <version>1.6.0-beta1</version> </dependency> <dependency> <groupId>docs-to-pdf-converter</groupId> <artifactId>docs-to-pdf-converter</artifactId> <version>1.8</version> </dependency>
代码实现:ui
//word模板替换 XWPFTemplate template = XWPFTemplate.compile("/Users/andy.l.an/IdeaProjects/ibuild-cscec82-contract/ibuild-cscec82-contract-portal/src/main/resources/word/subcontract/template/template.docx").render(new HashMap<String, Object>(){{ put("title", "Poi-tl 模板引擎Poi-tl 模板引擎Poi-tl 模板引擎Poi-tl 模板引擎Poi-tl 模板引擎Poi-tl 模板引擎Poi-tl 模板引擎Poi-tl 模板引擎Poi-tl 模板引擎Poi-tl 模板引擎Poi-tl 模板引擎Poi-tl 模板引擎"); }}); FileOutputStream out = new FileOutputStream("/Users/andy.l.an/IdeaProjects/ibuild-cscec82-contract/ibuild-cscec82-contract-portal/src/main/resources/word/subcontract/template/out_template.docx"); template.write(out); //word转换pdf FileOutputStream pdfout = new FileOutputStream("/Users/andy.l.an/IdeaProjects/ibuild-cscec82-contract/ibuild-cscec82-contract-portal/src/main/resources/word/subcontract/template/out_template.pdf"); DocxToPDFConverter docxToPDFConverter = new DocxToPDFConverter(new FileInputStream(new File("/Users/andy.l.an/IdeaProjects/ibuild-cscec82-contract/ibuild-cscec82-contract-portal/src/main/resources/word/subcontract/template/out_template.docx")), pdfout, true, true); docxToPDFConverter.convert(); out.flush(); out.close(); template.close();
踩坑记:3d
中文转换为空:blog
系统须要装word使用的字体:模板引擎
mac: 已经要把字体放到/Library/Fonts 目录下, 仅仅经过字体集安装不行源码