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();
相关推荐
zyplayer-doc2 小时前
重写OFD查看器,完善PDF查看器,增加搜索历史记录、滚动分页、目录排序等,zyplayer-doc 2.5.7 发布啦!
pdf·编辑器·飞书·开源软件·创业创新·有道云笔记
傻啦嘿哟3 小时前
Python实现PDF文档高效转换为HTML文件:从基础到进阶的完整指南
python·pdf·html
流浪猪头拯救地球7 小时前
利用 Python 解密 / 加密 PDF 文件
python·pdf·php
兰琛7 小时前
Android Compose展示PDF文件
android·pdf
Aevget7 小时前
界面控件DevExpress WPF v25.1新版亮点:PDF Viewer功能全新升级
pdf·wpf·界面控件·devexpress·ui开发
Olafur_zbj8 小时前
【AI】使用OCR处理pdf
数据库·pdf·ocr
Cyclo-16 小时前
PDFJS 在React中的引入 使用组件打开文件流PDF
前端·react.js·pdf
E_ICEBLUE1 天前
三步完成 Markdown 到 Word/PDF 的转换:Python 教程
python·pdf·word·markdown·格式转换
傻啦嘿哟1 天前
Python将Excel工作表转换为PDF:从入门到实战
python·pdf·excel
造价女工1 天前
PDF图纸合并:高效整合分散文件,项目归档更轻松
pdf