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();
相关推荐
qqqahhh14 小时前
xml文件的动态化配置,导入
xml·spring·springboot
Arenaschi17 小时前
关于垃圾的CSDN
java·网络·chrome·笔记·其他·oracle·pdf
开开心心就好17 小时前
内存清理工具开源免费,自动优化清理项
linux·运维·服务器·python·django·pdf·1024程序员节
开开心心_Every17 小时前
图片批量压缩工具:支持有损无损两种模式
python·游戏·微信·django·pdf·excel·语音识别
吴声子夜歌18 小时前
Maven——pom.xml详解
xml·java·maven
Charlie_lll20 小时前
LibreOffice 实现 Word 转 PDF
java·spring boot·pdf·word
Java后端的Ai之路20 小时前
【AI大模型开发】-基于向量数据库的PDF智能问答系统(实战)
人工智能·pdf·向量数据库·智能问答系统
iSee8572 天前
struts2 XML外部实体注入漏洞复现(CVE-2025-68493)
xml·安全·struts2
zhangfeng11332 天前
[图书推荐]1000本电子书的开源项目 pdf
pdf
SunnyDays10112 天前
Java 旋转 PDF 页面完整指南(含示例)
java·pdf·pdf页面旋转·旋转pdf页面