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();
相关推荐
码农娟17 小时前
Hutool XML工具-XmlUtil的使用
xml·java
夕阳之后的黑夜1 天前
Python脚本:为PDF批量添加水印
开发语言·python·pdf
码农娟1 天前
Hutool XML工具-XmlUtil遇到标签问题
xml
夏沫mds1 天前
Node.js 实现高保真 PDF 压缩:从 Canvas 方案到 Ghostscript 的踩坑实录
pdf·node.js
开开心心_Every2 天前
家长控制电脑软件:定时锁屏管理使用时长
网络协议·tcp/ip·游戏·微信·pdf·excel·语音识别
开开心心就好2 天前
免费抽奖工具支持批量导入+自定义主题
linux·运维·服务器·macos·pdf·phpstorm·1024程序员节
草履虫建模2 天前
A02 Maven 基础配置:本地仓库、镜像、项目编码与常见问题(IDEA 实战)
xml·java·spring boot·spring·maven·intellij-idea·idea
pass_port_csdn2 天前
zotero搬家,迁移换机/重装100% 完美克隆指南:文献PDF、插件配置、文献分类、标签、笔记等所有信息全克隆
笔记·pdf·zotero
开开心心_Every2 天前
电脑定时休息软件:久坐提醒养成活动习惯
游戏·微信·pdf·excel·语音识别·散列表·启发式算法
vlln2 天前
【调研报告】PDF解析技术现状与趋势:从人类阅读到大模型适配的需求
pdf