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();
相关推荐
海绵波波1071 天前
Zotero使用(一)PDF文件导入不会自动识别
pdf
2401_856926931 天前
图片转PDF技巧揭秘:四款高效工具推荐!
学习·pdf·图片转pdf·图片转pdf工具
readmancynn1 天前
XML_Tomcat_HTTP
xml·http·tomcat
我是全栈架构师1 天前
Dom4j使用xpath查询xml文
xml
cyt涛1 天前
MyBatis之手动映射
xml·数据库·mybatis·查询·resultmap·手动映射
齐 飞1 天前
使用jackson将xml和对象、List相互转换
xml·java·spring boot·后端·list
alex18011 天前
python实现多个pdf文件合并
java·python·pdf
代码代码快快显灵2 天前
XML标记语言
xml·java·数据库
似璟如你2 天前
Vue点击按钮生成pdf文件/Vue点击按钮生成png图片
pdf
deephub2 天前
概率分布深度解析:PMF、PDF和CDF的技术指南
人工智能·python·机器学习·pdf·概率论