通过spire.doc.free将word转换成PDF时存在缺陷:只能获取前3页。获取全文另外需支付费用。
使用documents4j,documents4j会保留原word文件中更多的样式,如修订模式下的差异化字体颜色、文档右侧修订记录等。
1.引入Pom
- <dependency>
- <groupId>com.documents4j</groupId>
- <artifactId>documents4j-local</artifactId>
- <version>1.0.3</version>
- </dependency>
- <dependency>
- <groupId>com.documents4j</groupId>
- <artifactId>documents4j-transformer-msoffice-word</artifactId>
- <version>1.0.3</version>
- </dependency>
2. xml2pdf方法如下,xmlpath是xml文件地址,pdfPath是生成的pdf地址。
-
- public void xml2pdf(String xmlPath,String pdfPath) throws IOException {
- // 参考:https:
- //blog.csdn.net/ka3p06/article/details/125476270 通过documents4j实现
- InputStream docxInputStream = null;
- OutputStream outputStream = null;
- try {
- // 原word地址
- docxInputStream = new FileInputStream(xmlPath);
- // 转换后pdf生成地址
- outputStream = new FileOutputStream(pdfPath);
- IConverter converter = LocalConverter.builder().build();
- converter.convert(docxInputStream)
- .as(DocumentType.XML)
- .to(outputStream)
- .as(DocumentType.PDF).execute();
- // 关闭
- converter.shutDown();
- // 关闭
- outputStream.close();
- // 关闭
- docxInputStream.close();
- } catch (Exception e) {
- System.out.println("[documents4J] word转pdf失败:" + e.toString());
- } finally {
- if (outputStream != null) {
- outputStream.close();
- }
- if (docxInputStream != null) {
- docxInputStream.close();
- }
- }
- }
只需改如下
converter.convert(docxInputStream)
.as(DocumentType.DOCX)
.to(outputStream)
.as(DocumentType.PDF).execute();