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();
相关推荐
Highcharts.js41 分钟前
适合报表系统的可视化图表|Highcharts支持直接导出PNG和PDF
javascript·数据库·react.js·pdf
XZHOUMIN7 小时前
【生成pdf格式的报告】
c++·pdf·mfc
汤姆百宝箱7 小时前
2026河北省初中学业水平摸底考试物理试卷(完整电子版pdf)
pdf
研來如此9 小时前
tinyxml2 常用读取接口对照表
xml·c++·tinyxml2
优化控制仿真模型10 小时前
【26年最新英语六级真题】2015-2025年12月英语六级历年真题及答案PDF电子版+六级核心词汇
经验分享·pdf
wtsolutions10 小时前
PDF to Image PDF - 一款强大的PDF转换图片/图片版PDF工具
pdf
wtsolutions10 小时前
PDF to Image PDF - A Powerful PDF to images, image-based-pdf Conversion Tool
pdf
优化控制仿真模型12 小时前
【26年英语四级】2015-2025年12月英语四级历年真题及答案PDF电子版(含听力音频)
经验分享·pdf
看山是山_Lau12 小时前
PDF书籍自动生成目录
pdf
2403_8961775312 小时前
怎么批量创建带不同名字的PDF?推荐4种批量创建带不同名字的PDF方法
pdf