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();
相关推荐
开开心心_Every12 小时前
Word转PDF工具,免费生成图片型文档
网络·笔记·pdf·word·powerpoint·excel·azure
一个无名的炼丹师13 小时前
[硬核实战] 解锁多模态RAG:构建能“看懂”PDF复杂图表的智能问答系统
人工智能·python·pdf·多模态·rag
jiayong2315 小时前
Spring XML解析与BeanDefinition注册详解
xml·java·spring
非凡ghost1 天前
Xournal++(PDF文档注释工具) 中文绿色版
学习·pdf·生活·软件需求
MonkeyKing_sunyuhua1 天前
使用ARQ做PDF OCR和 图片OCR的任务的方案
pdf·ocr
2501_930707782 天前
如何使用C#代码在 PDF 中添加或删除附件
pdf
m5655bj2 天前
如何使用 Python 调整 PDF 页面顺序?
python·pdf
就叫飞六吧2 天前
Spring 框架中的 Bean 继承:`parent` 属性 (XML配置)
xml·java·spring
YuanYWRS2 天前
办公基础:实现PDF中表单不改变格式的情况下转成excel
pdf·excel
极客智造2 天前
深入解析.NET 中的 XDocument:解锁 XML 处理的高级特性
xml·.net