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();
相关推荐
汤姆宝库16 小时前
法考历年真题及答案解析合集pdf版(2002-2025年)
pdf·法考
优化控制仿真模型17 小时前
2026【英一】考研英语一历年真题及答案解析PDF电子版(1980-2025年)
考研·pdf
云月呀2 天前
《死亡回忆录》藏汉双语版电子版 PDF,穆迪博士 150 例濒死体验访谈,一部关于生死的温柔读本
pdf·死亡回忆录
郭小李2 天前
mybatis的 Mapper.xml语法
xml·java·mybatis
步行cgn2 天前
为什么既要 web.xml 又要 springmvc.xml?能不能只配一个?
xml·前端·hive
xiaolinudao1232 天前
给pdf文件盖骑缝章的软件有哪些
pdf
hu55667983 天前
如何使用Adobe Acrobat Pro DC将1页PDF切割为2页,A3变A4打印。
pdf
ComPDFKit3 天前
PDF转Word后,每行都成一段?先分清断段、文本框和扫描页
pdf·word
Nymph_Zhu3 天前
pdf转换markdown预览及内容互相点击定位
前端·pdf·vue3·markdown·element-plus
web打印社区3 天前
Lodop在Edge和双核浏览器-先分清内核
前端·javascript·edge·pdf·ecmascript·html5