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();
相关推荐
正在走向自律7 小时前
实战心得:利用PaddleOCR彻底解决大模型无法解析图片型PDF的问题
开发语言·pdf·视觉检测·paddleocr·视觉模型·离线ocr识别
AI原来如此8 小时前
零基础教程:50页PDF一键浓缩成1页摘要
人工智能·ai·pdf·大模型
186******205318 小时前
PDF 转 Word 高效办公实战指南
pdf·word
随手工具-Excel, pdf, SQL8 小时前
PDF删除页面怎么操作?免费在线删除PDF指定页面,无需安装软件
pdf
SunnyDays101119 小时前
Java 实现 PDF 页面删除、排序、旋转和裁剪
java·pdf
zyplayer-doc1 天前
个人 AI 知识库怎么搭建:用 zyplayer-doc 把笔记、PDF 和图片资料变成可问答的第二大脑
大数据·开发语言·人工智能·笔记·pdf·ocr
日日行不惧千万里1 天前
Java AI 完整学习笔记
pdf
听风吹等浪起2 天前
002:多图合并导出PDF【网页版】
计算机视觉·pdf
蝶恋舞者2 天前
NMC-G2网络管理卡 资料官网下载流程
pdf
前网易架构师-高司机2 天前
带标注的山体滑坡塌方数据集数据集,识别率78.1%,974张图,支持yolo,coco json,voc xml,文末有模型训练代码
xml·yolo·json·数据集·自然灾害·山体滑坡