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();
相关推荐
面包资料屋7 小时前
2025年12月四级真题第1套PDF共9页
pdf
The Sheep 20237 小时前
C# 操作XML
xml·前端·c#
softbangong7 小时前
816-批量将图片分别转为pdf,文件夹下所有图片转为一个pdf
java·服务器·pdf·图片处理·图片转pdf·pdf工具·批量转换
熊猫钓鱼>_>9 小时前
MinerU的正确使用方式:如何解析PDF成标准化向量数据,以供AI大模型等场景应用
人工智能·阿里云·架构·pdf·ocr·skill·mineru
SEO-狼术10 小时前
Capture Freehand Ink Annotations in PDFs
pdf·.net
SEO-狼术11 小时前
Plan Projects Easily with Built-in Gantt Tools
pdf·.net
December31011 小时前
借助哪些软件工具可以实现在PDF上做批注?
pdf·pdf编辑·pdf批注·pdf注释
新缸中之脑11 小时前
LiteParse:理解布局的PDF解析器
pdf
开开心心就好1 天前
免费自媒体多功能工具箱,图片音视频处理
人工智能·pdf·ocr·excel·音视频·语音识别·媒体
优化控制仿真模型1 天前
【英二】考研英语二历年真题及答案解析PDF电子版(1980-2025年)
经验分享·考研·pdf