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();
        }
    }
相关推荐
伏特加女孩的实验室8 分钟前
candence导出PDF
pdf·candence·原理图设计·硬件工程师日常
ictI CABL10 分钟前
MySQL数据库的数据文件保存在哪?MySQL数据存在哪里
java
鱼鳞_14 分钟前
Java学习笔记_Day20(二叉树)
java·笔记·学习
番茄去哪了19 分钟前
任务调度功能实现
java·开发语言·spring boot
想你的液宝28 分钟前
Spring Boot 中基于 AOP 的 Controller 统一日志打印方案
java·后端
天草二十六_简村人33 分钟前
阿里云SLS采集jvm日志(上)
java·运维·数据库·后端·阿里云·容器·云计算
_MyFavorite_41 分钟前
JAVA重点基础、进阶知识及易错点总结(15)缓冲流 + 转换流
java·开发语言·spring boot
诗词在线44 分钟前
诗词在线古诗词传播
人工智能·word·php
qq_333120971 小时前
头歌答案--爬虫实战
java·前端·爬虫
TT哇1 小时前
【项目】从“本地能跑”到“生产级部署”:Java + Docker 自动化部署深度复盘
java·docker·自动化