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();
相关推荐
泡海椒18 小时前
PDF 表格样式优化:jquick-pdf 边框、圆角、背景色
java·开发语言·pdf
泡海椒1 天前
jquick-pdf 表格实战:动态数据 PDF 报表生成
java·开发语言·pdf
泡海椒1 天前
jquick-pdf 表格行列尺寸控制实战:单元格合并的可行边界
java·开发语言·pdf
java_logo2 天前
Docker 部署 Gotenberg 完整教程:Compose 搭建文档转 PDF API
docker·pdf·chromium·libreoffice·文档转换·轩辕镜像·gotenberg
泡海椒2 天前
jquick-pdf 防止 PDF 内容分页断裂:keepTogether 属性妙用
java·开发语言·pdf
泡海椒2 天前
jquick-pdf 文本元素实战:段落、行内文本、制表符用法详解
java·开发语言·pdf
SamChan903 天前
Python 处理小语种 PDF 的编码坑:重音字符、连字与 (cid:xx) 乱码的解决方案
python·ai·pdf·机器翻译
微咣科技3 天前
平台化工业AI再突破|大捷智能携手岚图汽车,打造车身焊装智能设计行业标杆
pdf·音视频
执明wa3 天前
Android RecyclerView 多类型, 多种 Item
android·xml·开发语言·设计模式·android studio
我滴老baby3 天前
工业物联网数据库选型:把计算能力放回第一维度
数据库·人工智能·架构·pdf