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();
相关推荐
SunnyDays101117 小时前
Java 实现 PDF 转 PDF/A 和 PDF/A 转 PDF(超详细教程)
java·开发语言·pdf
dshudsnb17 小时前
PDF转Word的3种方法(无乱码/批量/高精度教程)
pdf·word
2601_9611940218 小时前
2026四级词汇闪过电子版|高频词+真题词速记PDF
数据库·python·django·pdf·pygame
许彰午18 小时前
在PowerBuilder里手写XML序列化——没有现成库的年代怎么拼报文
xml·linux·服务器
2601_9611940220 小时前
2026六级词汇资料电子版|大学英语六级核心词汇PDF
java·spring·eclipse·pdf·tomcat·hibernate
2601_9611940220 小时前
2026四级词汇表4500电子版|大学英语四级核心词汇PDF
pdf
2601_961194021 天前
2026初级会计实务公式总结大全|计算题公式手册PDF
java·spring·eclipse·pdf·tomcat·hibernate
阿酷tony1 天前
PDF文档二维码和图文二维码如何生成(支持代码调用)
pdf·pdf二维码·图文二维码·pdf文档二维码·文档转二维码
AI刀刀1 天前
Kimi 保存 pdf 显示该页的尺寸超出范围令人困扰,AI 导出鸭一键修复参数,导出 PDF 更顺畅
人工智能·pdf·ai导出鸭
坚果的博客2 天前
鸿蒙PC三方库适配OAT.xml 与 SHA512SUM 解读:开源合规与源码校验
xml·开源·harmonyos