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();
相关推荐
私人珍藏库1 小时前
【Windows】PDF超能助手(1.0.13)
windows·pdf·工具·软件·多功能
其实秋天的枫4 小时前
2026年新大纲普通话考试真题题库50套(PDF电子版)
经验分享·pdf
开开心心_Every5 小时前
文字转语音无字数限,对接微软接口比付费爽
运维·服务器·人工智能·edge·pdf·paddle·segmentfault
无心水6 小时前
2、5分钟上手|PyPDF2 快速提取PDF文本
java·linux·分布式·后端·python·架构·pdf
优化控制仿真模型7 小时前
2026年新大纲普通话考试真题题库50套(PDF电子版)
经验分享·pdf
SEO-狼术7 小时前
Aspose.PDF for .NET 24.5 Crack
pdf
其实秋天的枫7 小时前
考研英语一历年真题及答案PDF电子版(1998-2026年)
经验分享·pdf
优化控制仿真模型7 小时前
【27考研】考研英语一历年真题及答案PDF电子版(1998-2026年)
经验分享·pdf
搬代码7 小时前
wps压缩pdf压缩
pdf
qq_628515768 小时前
Java实现pdf导出
java·vue.js·react.js·pdf