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();
相关推荐
浩浩的科研笔记6 小时前
投论文常用技术笔记-使用visio导出贴合图像尺寸大小的PDF(无白边、无黑框)
笔记·pdf·论文笔记
开开心心_Every7 小时前
无广告干扰:简单好用文字LOGO设计工具
xml·java·网络·数据库·华为od·华为云·excel
m5655bj8 小时前
如何通过 C# 将 Markdown 转换为 PDF 文档
开发语言·pdf·c#
stereohomology8 小时前
解决某些Typora主题导出PDF分页拦腰截断文字或图片等问题的方法
pdf
武子康9 小时前
Java-210 Spring AMQP 整合 RabbitMQ:JavaConfig 注解配置、RabbitTemplate 发送/同步接收与坑位速查
xml·java·spring·消息队列·rabbitmq·java-rabbitmq·mq
jiayong239 小时前
`.flattened-pom.xml` 深度解析
xml
小李飞飞砖10 小时前
RemoteViews的layout无法设置xml类型的Drawable,会报错
xml
小二·10 小时前
AI工程化实战《四》:多模态 RAG 全解——让 AI 看懂 PDF 表格、扫描件与流程图
人工智能·pdf·流程图
武子康10 小时前
Java-209 Spring AMQP 整合 RabbitMQ 实战:XML 配置直连交换机、RabbitAdmin 自动声明与收发闭环
xml·java·spring·rabbitmq·java-rabbitmq·java-activemq
这个需求建议不做1 天前
pdf.js(pdfdist)踩坑workerSrc报错pdf.worker.mjs无法正确获取
开发语言·javascript·pdf