java word导出pdf

整体思路就是: 使用word模板引擎,将占位符(格式:{{title}})替换为查询出来的数据,再将替换完成的word转换为pdf

doc转pdf源码: https://gitee.com/java\_long/docs-to-pdf-converter.git

word模板引擎: https://github.com/Sayi/poi-tl.git

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**_>

代码实现:

//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()_;

踩坑记:

中文转换为空:

系统需要装word使用的字体:

mac: 已经要把字体放到/Library/Fonts 目录下, 仅仅通过字体集安装不行

评论

h
hw_7864

⭐️ Admin快速开发: https://show.cool-admin.com/

赞 0
h
hw_7864

⭐️ 官方文档: https://cool-js.com

赞 0
h
hw_7864

⭐️ chatgpt在线体验: https://cool-js.com/ai/chat-vip/index.html?r=helloworld

赞 0