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();
相关推荐
祭曦念19 小时前
ArkUI声明式UI入门:从XML到声明式的思维转变
xml·ui·鸿蒙
2501_930707782 天前
使用C#代码替换 PDF 文档中的文本
pdf
周末也要写八哥2 天前
Visual C++6.0下载安装流程及PDF学习手册资源
c++·学习·pdf
优化控制仿真模型2 天前
2026初中英语考纲词汇表(1600词)PDF电子版
经验分享·pdf
2401_876964132 天前
27考研优路|肖睿|唐辛|师大集训营|大牙|B站橙啦101公共课PDF
考研·pdf
2401_876964132 天前
27余峰|苏一|大李子|鹿吖101公共课托管班网课PDF
pdf
SEO-狼术2 天前
Visualize Trends with Bar Charts
pdf·.net
私人珍藏库2 天前
【PC】[吾爱大神原创工具] PDFImageViewer V1 永久免费的PDF图像查看和导出工具
windows·pdf·工具·软件·多功能
小饕2 天前
RAG 数据加载全攻略:从文本到 PDF 的 Loader 选型指南
人工智能·pdf
其实秋天的枫2 天前
【26年】考研数学一、二、三历年真题及答案解析PDF电子版(1987-2026年)
经验分享·pdf