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();
相关推荐
海带紫菜菠萝汤6 小时前
免费在线翻译器横评:2026年6款PDF翻译工具对比
人工智能·python·pdf
SunnyDays10116 小时前
C# 加密和解密 PDF:设置密码、AES 加密及操作权限
pdf·c#·加密 pdf·解除 pdf 密码·pdf 权限设置·pdf 文档安全
SamChan908 小时前
WebSocket实现PDF翻译进度实时推送:Go后端+React前端的完整方案
前端·websocket·pdf·c#·react·机器翻译
w67820071 天前
,攻击者通过构造特殊的XML使其包含恶意外部实体。外部实体可以为服务器敏感文件,也可以为网络请求等,之后利用方式类似于文件包含和SS ...
xml·服务器·网络
森叶1 天前
拆解 PDF 翻译引擎:表格纹丝不动、长语言自动缩放、图片文字 AI 重绘背后的工程
人工智能·pdf
name好难取诶1 天前
解析请求体内容(如 JSON、表单数据、XML 等) 将原始数据转换为 Python 数据结构 使转换后的数据可在 request. ...
xml·python·json
qq_171538851 天前
深入浅出 MyBatis XML:从入门到精通
xml·java·mybatis
AI创界者1 天前
MinerU v3.4.4 离线部署实战:PDF/PPT/图片一键转 Markdown,低至 4G 显存/纯 CPU 可用
pdf·powerpoint
cosinmz1 天前
图片转PDF:手机合同照片如何整理成规范PDF文件
pdf·pdf转换·图片转pdf·图片转pdf小程序
a1117761 天前
深入理解 AI Agent PDF(设计原理与工程实践 )
pdf