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();
相关推荐
南风微微吹3 小时前
计算机二级MS Office历年真题试题及答案解析40套电子版PDF(含操作题和选择题)
pdf
小幂同学9 小时前
CAD图纸怎么转PDF和图片?CAD快速看图王(幂果)转换方法解析
pdf·cad
weixin_4692738112 小时前
银行流水 PDF 转 Excel 或者 CSV 完整指南
人工智能·pdf·excel
AI导出鸭16 小时前
腾讯ima的LaTeX生成PDF文件复制后数学公式乱码,怎样修改?AI导出鸭苹果版硬核拆解
人工智能·pdf·ai导出鸭
辣香牛肉面18 小时前
Wondershare PDFelement Professional v12.1.24.4310+OCR 万兴PDF编辑器
pdf·编辑器·ocr
点我头像干啥1 天前
004:多个PDF文件合并
开发语言·pdf·php
DS随心转插件2 天前
ChatGPT生成的pdf怎么导出 只要加个“AI导出鸭”
人工智能·chatgpt·pdf·deepseek·ai导出鸭
AI导出鸭2 天前
ChatGPT的LaTeX生成PDF文件复制后数学公式乱码,怎样修改?苹果用户的底层逻辑与优雅解法
人工智能·chatgpt·pdf·ai导出鸭
听风吹等浪起2 天前
004:多个PDF合并成一个PDF【网页版】
pdf·状态模式