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();
相关推荐
开开心心就好1 小时前
定时结束进程的小工具,到点还能关机
linux·运维·服务器·智能手机·pdf·电脑·word
充值内卷4 小时前
从 WAML 到 PDF 阅读器:PentPDF 开发过程
pdf
Matt Feng5 小时前
PDF批量转图片:DPI、命名规则和长图怎么设
pdf·wps
Matt Feng6 小时前
PDF水印分4类:哪些能删,哪些删了会伤正文
pdf·wps
凤城老人9 小时前
开源少儿编程教材《代码岛》:41 讲 Python 入门,PDF/EPUB 免费下载
python·pdf·pygame
福兮说13 小时前
PDF 文件提取页面后发现文件体积反而变大?分析底层对象流与冗余结构
pdf
Matt Feng1 天前
PDF加水印和密码:6项权限设置与完整步骤
pdf·word·wps
泡海椒1 天前
Java PDF 报表开发:一页简历的两种版式风格对比与折行避坑
java·开发语言·pdf
灵析表格1 天前
灵析表格函数精讲|xml转json:供应商配置转换
xml·json·excel·办公自动化·wps·效率工具·ai办公
奔跑的呱呱牛1 天前
两张发票印在一张 A4 上:宇境自研的聆境 PDF,完全免费
pdf