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 小时前
PDF 翻译工具横评与自建批量方案:从在线工具到 Python 自动化
python·pdf·自动化
百事牛科技6 小时前
办公文档防护:如何限制 PDF 转换成其他格式文件
windows·pdf
SunnyDays10117 小时前
Java 给 PDF 添加页码:实现“第 X 页,共 Y 页”
java·pdf·页码
2601_965912837 小时前
520MB卷宗合并压缩踩坑实录:PDF文档归档场景的技术选型与性能对比
pdf
霸道流氓气质7 小时前
本地用 Ollama + 视觉模型识别 PDF 技术教程
pdf
经典19929 小时前
解析pdf表格内容
windows·pdf
星花月11 小时前
【无标题】
ai·语言模型·pdf·deep learning
E_ICEBLUE11 小时前
Python 办公自动化:将 PowerPoint (PPT/PPTX) 转换为 PDF 【全面指南】
python·pdf·powerpoint
数据知道1 天前
XXE 漏洞深度实战:XML 外部实体攻击与 OOB 带外
xml·网络·安全·网络安全
云水一下1 天前
零基础玩转bWAPP靶场(四十七):XSS - Reflected (AJAX/XML)
xml·web安全·ajax·xss·bwapp