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();
相关推荐
复园电子4 小时前
跨平台PDF签名解析器设计:多方签署与自签名证书(野鸡CA)过滤
pdf·电子合同
AI导出鸭PC端7 小时前
预览即导出:告别AI文档格式崩塌,网页预览效果1:1落地Word
人工智能·pdf·word·流程图·豆包·ai导出鸭
hu55667987 小时前
小规模纳税人财务报表报送后如何导出报送pdf
pdf
__zRainy__8 小时前
基于计数信号量(Counting Semaphore)的 PDF 渲染并发控制方案
pdf
C137的本贾尼8 小时前
第九篇:微服务与分布式——把一个大系统拆成多个小服务
xml·spring boot·后端
工具派10 小时前
从 git commit 到交付 PDF:我的一条在线工具流实录
git·elasticsearch·pdf
Li Ming&1 天前
Python办公自动化:利用Python批量将PDF转换为图片文件
python·pdf·pip
ji_shuke1 天前
Vue3 前端批量打印 PDF/图片踩坑记:跨域、合并打印、对话框闪退与按钮一直 loading
前端·pdf·状态模式·pdf打印
Am-Chestnuts1 天前
Mermaid流程图怎么导出Word/PDF?DS随心转批量保存AI多轮修改与源码
pdf·aigc·word·流程图
FL16238631291 天前
pdf批量转ofd本地离线操作简单支持win10及以上系统
pdf