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();
相关推荐
蛋王派1 小时前
本地部署DeepSeek-OCR:打造高效的PDF文字识别服务
人工智能·自然语言处理·pdf·ocr
Iloveskr1 小时前
markdown转为pdf导出
java·pdf
huluang5 小时前
XML文档差异分析工具:深入解析Word XML结构变化
xml·word
Source.Liu8 小时前
【PDF】PDF文件体详解
pdf
非凡ghost8 小时前
批量转双层PDF(可识别各种语言) 中文绿色版
前端·windows·pdf·计算机外设·软件需求
夏之繁花8 小时前
PDFelement 万兴PDF,简单好用的PDF阅读编辑批注器
pdf
打小就很皮...8 小时前
PDF 下载弹窗 content 区域可行性方案
前端·javascript·pdf
未孤_有青山21 小时前
库卡机器人通讯-EtherKRL-XML格式
xml·c#
拓端研究室21 小时前
专题:2025机器人产业的变革与展望白皮书:人形机器人与工业机器人洞察|附130+份报告PDF、数据、绘图模板汇总下载
人工智能·机器人·pdf
qq_4203620321 小时前
PDF导出服务
前端·pdf·状态模式·node·puppeteer