java 使用documents4j将XML转为pdf文件的方式

1.背景:

通过spire.doc.free将word转换成PDF时存在缺陷:只能获取前3页。获取全文另外需支付费用。

2.解决办法

使用documents4j,documents4j会保留原word文件中更多的样式,如修订模式下的差异化字体颜色、文档右侧修订记录等。

3.具体步骤

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>
  1. 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();
             }
         }
     }

4. documents4j也可以把word转为pdf

只需改如下

复制代码
converter.convert(docxInputStream)
                    .as(DocumentType.DOCX)
                    .to(outputStream)
                    .as(DocumentType.PDF).execute();
相关推荐
拓端研究室2 小时前
专题:2025构建全自动驾驶汽车生态系统:中国智能驾驶行业全景研究报告|附80+份报告PDF、数据仪表盘汇总下载
pdf·自动驾驶·汽车
南风微微吹3 小时前
【管综】考研199管理类联考真题试卷及答案解析PDF电子版(2009-2025年)
考研·pdf
有过~11 小时前
Total PDF Converter v6.5.0.356.0 电脑PDF多功能转换器
pdf
E_ICEBLUE19 小时前
Python 教程:如何快速在 PDF 中添加水印(文字、图片)
开发语言·python·pdf
缺点内向1 天前
Java: 为PDF批量添加图片水印实用指南
java·开发语言·pdf
百***37481 天前
【mybatis】基本操作:详解Spring通过注解和XML的方式来操作mybatis
xml·spring·mybatis
造价女工1 天前
PDF转图片:轻松实现工程图纸的高效共享与高清展示
pdf·格式工厂
涔溪1 天前
vue中预览pdf文件
前端·vue.js·pdf
lyx_20161 天前
PDF文档导出分页功能实现
react.js·typescript·pdf·react
puyaCheer1 天前
Android 打开 在线 pdf 文件
android·pdf