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();
相关推荐
御坂嘀喵 白日焰火3 小时前
LINQ之路18:LINQ to XML之导航和查询
xml·solr·linq
2601_965912914 小时前
PDF转Word工具深度横评:2026年国内免费方案技术对比
pdf·word
残月心殇 请珍惜枸6 小时前
LINQ之路17:LINQ to XML之X-DOM介绍
xml·solr·linq
2501_930707786 小时前
使用C#代码将PDF转化为线性PDF文件
pdf
诸葛大钢铁6 小时前
PDF无法复制文字怎么办?3种方法解除PDF复制限制并提取文字
pdf·ocr·pdf教程·pdf解除限制·pdf无法复制·pdf文字识别
2501_930707788 小时前
使用C#代码调整 PDF 版本
pdf
wtsolutions9 小时前
PDF-to-Image-PDF的安全优势 - 保护您的文档和数据
pdf
qq_366624789 小时前
在线PDF翻译工具在多语言技术文档处理中的实战应用
microsoft·pdf
肖恭伟10 小时前
MinerU 新手完整配置教程:Windows 下将 PDF 转为带图片的 Markdown
windows·pdf
开开心心_Every10 小时前
电脑文件搜索软件支持内容和拼音搜索
linux·服务器·人工智能·r语言·pdf·音视频·symfony