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();
相关推荐
小脑斧12314 小时前
Adobe PDF 编辑器 破截一键激火
adobe·pdf
qq_2837200515 小时前
Python3 模块精讲|PyPDF2 万字实战:PDF 读写、拆分、合并、加水印一站式搞定
pdf·#办公自动化·#pypdf2·#pdf 处理·#python 实战
William.csj15 小时前
科研——PPT导出高清PDF的方法
pdf·ppt
开开心心_Every15 小时前
跨平台高速下载工具,支持浏览器功能强大
运维·服务器·随机森林·pdf·电脑·逻辑回归·excel
daanpdf15 小时前
永乐大典pdf电子版(现存最全版本)
pdf
好运的阿财16 小时前
OpenClaw工具拆解之 image+pdf
人工智能·python·程序人生·pdf·ai编程·openclaw·openclaw工具
java1234_小锋1 天前
MyBatis中XML映射有哪些标签?
xml·tomcat·mybatis
大腕先生1 天前
通用分页超详细介绍(附带源代码解析&页面展示效果)
xml·java·linux·服务器·开发语言·前端·idea
开开心心就好2 天前
避免借电脑尴尬的故障模拟工具
科技·游戏·visualstudio·edge·pdf·电脑·powerpoint
南风微微吹2 天前
全国事业单位联考A、B、C、D、E类历年真题及答案解析PDF电子版(2015-2025年下)
pdf·考公