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();
相关推荐
wtsolutions16 小时前
QMT 知识库 XtQuant知识库 使用文档 pdf
pdf·知识库·文档·qmt
波诺波17 小时前
最小 SOFA XML 场景结构 0-base.scn
xml·java·前端
海盗123419 小时前
C#中PDF操作-QuestPDF介绍和使用教程
pdf·c#
半月夏微凉19 小时前
win11下不能预览pdf的问题解决方法
windows·pdf
猫猫不是喵喵.19 小时前
vue2技术栈将表单内容转为PDF并下载
pdf
庖丁AI2 天前
合同比对工具怎么选?Word、PDF 和扫描件差异对比思路
pdf·word
包子源2 天前
PDF 转 Word/Excel 全链路实战:Next.js + 阿里云文档智能
pdf·word·excel
敲代码的鱼哇2 天前
PDF 预览与签名批注写回 支持安卓 iOS 鸿蒙 UTS插件
android·ios·pdf·鸿蒙·harmony
开开心心_Every3 天前
能把网页藏在Word里的实用摸鱼工具
人工智能·科技·目标跟踪·pdf·计算机外设·语音识别·mllib
夕除3 天前
spring boot 14
xml·spring boot·redis