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();
相关推荐
爱喝水的鱼丶14 小时前
SAP-ABAP:SAP 简单报表输出开发系列(共6篇) 第五篇:SAP 报表多格式输出:Excel/PDF 批量导出功能实现
学习·性能优化·pdf·excel·sap·abap
le16161616 小时前
Android Compose基础布局——从传统XML的视角切入了解
xml·compose
cosinmz21 小时前
PDF 发票合并经验分享:月初高效整理发票的实用方法
经验分享·小程序·pdf·pdf转换·pdf发票合并·发票合并打印
一个博客21 小时前
pdf-viewer 实现预览pdf文件
开发语言·javascript·pdf
代码小库21 小时前
免费在线简历工具「面试帮」——18 款模板 + PDF 导出
面试·职场和发展·pdf
庖丁AI21 小时前
文档比对工具怎么选?Word、PDF、扫描件差异检测思路
pdf·word·扫描件·文档比对
asdzx671 天前
使用 Python 快速提取 PDF 中的表格
python·pdf
南风微微吹1 天前
2026英语六级作文模版万能句子PDF电子版
pdf·英语六级
又是被bug折磨的一天1 天前
对多个pdf合同文件批量命名
pdf
南风微微吹1 天前
2026年英语四级作文模版万能句子PDF电子版
pdf·英语四级