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();
相关推荐
开开心心_Every11 小时前
实现鼠标键盘动作录制与重复播放的工具
微信·jupyter·pycharm·pdf·计算机外设·word·excel
2601_9622994914 小时前
使用 Python 将 CSV 转为 PDF(含表格样式美化)
python·pdf·csv·spire.xls·表格样式
tianyue10021 小时前
PDFsam Basic PDF 分割、合并
pdf
SunnyDays10111 天前
如何使用 Python 给 PDF 添加附件:文档附件与附件注释
开发语言·python·pdf
SamChan901 天前
PDF翻译服务端到端基准测试:4款主流方案的吞吐量、延迟、内存占用对比
服务器·网络·python·ai·pdf·wpf
Felicia-侧听1 天前
PDF怎么转换成Word?3种方法实现PDF转可编辑Word
pdf·word·pdf转word
乘风归趣1 天前
spire.doc.free将word中占位符替换为pdf文件,以及合并PDF
pdf·word
spencer_tseng2 天前
[j2cache ehcache.xml]/tmp/.ehcache-diskstore.lock (Permission denied)
xml·linux·python·ehcache·[j2cache
庖丁AI2 天前
PDF 转 Markdown 工具怎么选?AI 知识库和 RAG 场景要注意什么
人工智能·pdf·文档解析
几层山下2 天前
WPS的word文档转pdf java实现不乱格式生成-已解决
java·pdf·word·wps