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();
相关推荐
拓端研究室5 小时前
2025医疗健康行业革新报告:AI赋能、国际化|附170+份报告PDF、数据、可视化模板汇总下载
人工智能·pdf
编程修仙6 小时前
第十一篇 Spring事务
xml·java·数据库·spring
金士顿8 小时前
Ethercat耦合器添加的IO导出xml 初始化IO参数
android·xml·java
小年糕是糕手10 小时前
【C++】类和对象(六) -- 友元、内部类、匿名对象、对象拷贝时的编译器优化
开发语言·c++·算法·pdf·github·排序算法
libolei12 小时前
压缩 pdf 文件大小 完全免费
pdf·pdf压缩
一只小羊啊13 小时前
Vue + Android WebView 实现大文件 PDF 预览完整解决方案
android·vue.js·pdf·webview
梅如你13 小时前
《从零开始构建智能体》PDF教程分享
pdf
团圆吧13 小时前
md2pdf.py:高效 Markdown 转 PDF 全能工具
python·pdf·tensorflow
qq_2965446513 小时前
在怎么编辑PDF?专业级pdf转换教程,PDF在线编辑,Word转PDF使用方法
microsoft·pdf·word
烤麻辣烫1 天前
黑马程序员苍穹外卖后端概览
xml·java·数据库·spring·intellij-idea