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();
相关推荐
qyyyyy57015 小时前
外文 PDF 怎么整理成 Markdown?从翻译、内容提取到 RAG 知识库导入
自然语言处理·pdf·erlang·机器翻译·零知识证明
AI导出鸭1 天前
Perplexity的LaTeX生成PDF文件复制后数学公式乱码,怎样修改?AI导出鸭苹果版的技术拆解与批量之道
人工智能·pdf·ai导出鸭
SpaceAIGlobal2 天前
AI PPT生成工具哪些支持PDF文档导入?
人工智能·ai·pdf·powerpoint·办公
欧特克_Glodon2 天前
OpenCV计算机视觉开发入门与实践<十二>:XML 和 YAML 文件读写
xml·c++·opencv·计算机视觉
程序员-珍2 天前
安卓开发:同名 styles.xml 在不同分支/文件夹的合并规则
android·xml·前端
Xxtaoaooo2 天前
极空间部署Stirling PDF:搭建自托管PDF工具箱并实现远程访问
pdf·cpolar·stirling pdf
SamChan902 天前
对比 4 种主流 PDF 文档解析方案:PyMuPDF vs pdfplumber vs Apache PDFBox vs 大模型 OCR
python·ai·pdf·ocr·apache·机器翻译
AI刀刀3 天前
Kimi 文档导出格式错乱、排版丢失、导出报错?AI 导出鸭一键智能适配,稳定输出规范 Word、PDF,高效解决各类导出难题
人工智能·pdf·word·ai导出鸭
Ai-_Man3 天前
豆包智能体把对话批量导出为Word或PDF的正确顺序
人工智能·ai·小程序·pdf·word
SamChan903 天前
FastAPI+Celery+Redis搭建企业级PDF翻译异步任务系统
redis·后端·python·pdf·wpf·fastapi