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();
相关推荐
2603_954138398 小时前
PDF 转 Word 工具深度评测:从参数解析到实战避坑
pdf·word
沉默王二11 小时前
LlamaIndex 开源 LiteParse,零云依赖搞定扫描件PDF
pdf·开源
啦啦啦~~~33013 小时前
【办公软件】开源的PDF合并分割工具!支持PDF拆分、合并、交替混合、页面旋转、提取页面等
阿里云·pdf·电脑·开源软件
tsfy200317 小时前
Python批量调整Excel格式,并排版导出PDF
python·pdf·excel
老陈聊架构18 小时前
『AI大模型』OpenDataLoader PDF 实战:RAG 知识库 PDF 解析与LangChain 接入
ai·langchain·pdf·rag·opendataloader
数字游民952720 小时前
PDF批量转Markdown工具:我用AI做了一个本地桌面版,也顺手想了想AI工具怎么落地
人工智能·ai·pdf·aigc·自媒体·数字游民9527
小米渣的逆袭21 小时前
macos上一个好用的PDF文字提取工具方案
macos·pdf
糖果店的幽灵21 小时前
软件测试接口测试从入门到精通:常见接口类型与数据格式
xml·软件测试·json·接口测试·数据格式
DS随心转插件1 天前
Kimi 转 pdf 怎么压缩但清晰?AI 导出鸭一站式优化,压缩文件同时留存原版高清内容
人工智能·ai·pdf·豆包·deepseek·ai导出鸭