java中word转为pdf

背景:由于前端vue无法实现复杂的word可视化插件,希望后端做个能将复杂word转为pdf的方案。(这里我最终使用的是documents4j)

java中word转为pdf

经过gpt、网上搜索、以及多方面的考量有以下几种方案。

  • 1.poi原生的转换,其优点就是免费开源,缺点就是工作量会很大,并且对于复杂文档无法做到足够的格式满足。
  • 2.Aspose.Words这一款商业三方插件,有点就是功能强大,缺点就是要钱。
  • 3.documents4j这款免费也符合现阶段功能,并且免费

实现documents4j

1.安装wps

2.代码

maven依赖

xml 复制代码
<!-- word转pdf start -->
      <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>
<!-- word转pdf end -->

java源码

java 复制代码
    public static void main(String[] args) {
        String wordPath= "0004简历.docx";
        String pdfPath = "output.pdf";
        converterToPdf(wordPath,pdfPath);
    }

    public static void converterToPdf(String wordPath, String pdfPath) {
        try {
            InputStream inputStream = new FileInputStream(wordPath);
            OutputStream outputStream = new FileOutputStream(pdfPath);
            IConverter converter = LocalConverter.builder().build();
            // 判断文档类型
            if (wordPath.contains(".doc")) {
                converter.convert(inputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
            } else {
                converter.convert(inputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
            }
            // 最后关闭流
            outputStream.close();
            inputStream.close();
            converter.shutDown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
相关推荐
小江的记录本几秒前
【分布式】分布式一致性协议:2PC/3PC、Paxos、Raft、ZAB 核心原理、区别(2026必考Raft)
java·前端·分布式·后端·安全·面试·系统架构
北风toto1 分钟前
RestTemplate 的入门使用,直接给上作者的项目Demo
java
疯狂打码的少年2 分钟前
JDK 7、8、13 和 20区别深度了解
java·开发语言
钝挫力PROGRAMER3 分钟前
Java中如何优雅管理接口的多个实现
java·设计模式
迷藏4946 分钟前
# 发散创新:基于Python的自动特征工程实战与深度优化在机器学习
java·开发语言·python·机器学习
开开心心就好10 分钟前
这款PPT计时工具支持远程控制功能
前端·科技·游戏·edge·pdf·全文检索·powerpoint
星晨雪海11 分钟前
查询区域列表并统计点位数量
java
Seven9712 分钟前
用300行代码手写一个mini版的Tomcat
java
隐退山林15 分钟前
JavaEE进阶:SpirngMVC入门(2)
java·java-ee
小江的记录本2 小时前
【分布式】分布式核心组件——分布式锁:Redis/ZooKeeper/etcd 实现方案(附全方位对比表)、优缺点、Redlock、时钟回拨问题
java·网络·redis·分布式·后端·zookeeper·架构