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();
相关推荐
Lucky_Turtle2 小时前
【论文写作】PDF图片不清晰,打印生成PDF空白大,PDF字体嵌入
开发语言·pdf·c#
工具派2 小时前
写技术文档时,我把Markdown编辑和PDF导出都搬到了浏览器
pdf
前网易架构师-高司机3 小时前
带标注的21种中药材识别数据集,识别率73.8%数据集,2237张图,支持yolo,coco json,voc xml,文末有模型训练代码
xml·yolo·json·数据集·中药·药材·中草药
杰佛史彦明13 小时前
PDF 表格转 CSV:Python 实现方法与代码解析
开发语言·python·pdf
复园电子16 小时前
解析PDF二进制结构:数字签名块(Signature Block)篡改异变分析
pdf
snow@li20 小时前
Java:pom.xml全景深度分析 / 机制、标签、依赖、打包、生产避坑全解 / 工程基石
xml·java·开发语言
田里的水稻21 小时前
EP_XML\JSON配置文件和YAML
xml·运维·人工智能·机器人·自动驾驶·json
AI导出鸭PC端21 小时前
豆包智能体停运在即,历史对话如何一键导出为 Word 或 PDF?
人工智能·pdf·word·豆包·ai导出鸭
不厌 -_-1 天前
VSCode 中 Markdown 转 PDF
vscode·pdf
xiangji1 天前
开源完美模块组件化可扩展的Xml解析器Hand.ParseXml
xml·模块化·组件化·可扩展