想系统学习的同志,可以参考 POI官方
1、导出依赖
<dependency> <groupId>fr.opensagres.xdocreport</groupId> <artifactId>fr.opensagres.poi.xwpf.converter.pdf-gae</artifactId> <version>2.0.1</version> </dependency>
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.2.0</version>
</dependency>
这里要注意版本问题!!
2、准备word稳当
3、实现代码1
/** * 将word模板转化成pdf * @param args * @throws Exception */ public static void main(String[] args) throws Exception { Map datas = new HashMap(); datas.put("title","我是活动标题"); //给{{title}}标识赋值 XWPFTemplate template = XWPFTemplate.compile("E:/test.docx"); template.render(datas);
//将word转成pdf PdfOptions options = PdfOptions.create(); try (OutputStream outPDF = Files.newOutputStream(Paths.get("E:/tes2.pdf"))) { PdfConverter.getInstance().convert(template.getXWPFDocument(), outPDF, options); } catch (IOException e) { e.printStackTrace(); } }
4、实现代码2,这里不考虑赋值问题,直接转换
public static void main(String[] args) { try {
//读取word文档 XWPFDocument document = null; try (InputStream in = Files.newInputStream(Paths.get("E:/test1.docx"))) { document = new XWPFDocument(in); } catch (IOException e) { e.printStackTrace(); }
//将word转成pdf PdfOptions options = PdfOptions.create(); try (OutputStream outPDF = Files.newOutputStream(Paths.get("E:/tes2.pdf"))) { PdfConverter.getInstance().convert(document, outPDF, options); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } }