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();
相关推荐
wangchensong4 小时前
深度解析:PDF 动态安全防线与 Lockbox 的防御逻辑
安全·pdf
还不秃顶的计科生4 小时前
latex代码裁剪pdf图片
pdf·latex
de_wizard17 小时前
【mybatis】基本操作:详解Spring通过注解和XML的方式来操作mybatis
xml·spring·mybatis
min18112345619 小时前
PC流程图模板大全 中文定制化满足不同行业需求
架构·pdf·流程图
min18112345619 小时前
组织结构图导出PDF 高清无水印在线生成
网络·人工智能·架构·pdf·流程图·copilot
拓端研究室21 小时前
2026机器人产业前沿洞察报告:人形与特种机器人,认证、制造到消费 | 附280+份报告PDF、数据、可视化模板汇总下载
机器人·pdf·制造
开开心心_Every21 小时前
PDF密码移除工具,解除打印编辑复制权限免费
linux·运维·服务器·pdf·web3·ocr·共识算法
缘于自然821 小时前
高通modem如何确定MBN选的是哪个carrier_policy.xml
xml·modem·mbn
C_心欲无痕1 天前
前端 PDF 渲染与下载实现
前端·pdf
ONLYOFFICE1 天前
ONLYOFFICE 文档 9.3 开发者版:PDF API、Office JavaScript API 新方法及更多功能
pdf·onlyoffice