java word导出pdf

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

76ac1bc3da6d1cec6f1c2f9406c8e07a768.jpg

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

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

pom依赖:

<dependency>
    <groupId>com.deepoovegroupId>
    <artifactId>poi-tlartifactId>
    <version>1.6.0-beta1version>
dependency>
<dependency>
    <groupId>docs-to-pdf-convertergroupId>
    <artifactId>docs-to-pdf-converterartifactId>
    <version>1.8version>
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 目录下, 仅仅通过字体集安装不行

你可能感兴趣的:(java word导出pdf)