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();
相关推荐
不想有bug的小菜鸟14 分钟前
vue3使用iframe全屏展示pdf效果
前端·pdf
best_virtuoso13 小时前
XML DOM4J 三、XPath
xml
IDRSolutions_CN18 小时前
(教程)PDF 字体技术入门
java·经验分享·pdf·软件工程·团队开发
步、步、为营18 小时前
解锁C# XML编程:从新手到实战高手的蜕变之路
xml·数据库·c#
恶猫1 天前
[特殊字符]清华大学:DeepSeek从入门到精通.pdf(清华领航,驾驭DeepSeek,开启AI新境界)
ai·pdf·deepseek
别拿曾经看以后~2 天前
【PDF预览】使用iframe实现pdf文件预览,加盖章
pdf
自然 醒2 天前
鸿蒙ArkTs如何实现pdf预览功能?
华为·pdf·harmonyos·harmonyosnext版本
Leo.yuan2 天前
48页PDF | GBT 36073-2018 数据管理能力成熟度评估模型 (附下载)
pdf
PythonFun2 天前
1分钟用DeepSeek编写一个PDF转Word软件
pdf·c#·word
C_V_Better2 天前
Java 接收 XML 格式参数并转换为 JSON
xml·java·开发语言·数据结构·后端·算法·json