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();
        }
    }
相关推荐
码农周12 分钟前
告别大体积PDF!基于PDFBox的Java压缩工具
java·spring boot
优化控制仿真模型16 分钟前
【26年6月四级】英语四级2015-2025年12月真题及答案+高频核心词汇1500个pdf电子版
经验分享·pdf
devilnumber21 分钟前
java中Redisson ,jedis,Lettuce和Spring Data Redis的四种深度对比和优缺点详解
java·redis·spring
摇滚侠22 分钟前
Java 进阶教程,全面剖析 Java 多线程编程
java·开发语言
yaaakaaang23 分钟前
十四、命令模式
java·命令模式
小锋java123440 分钟前
【技术专题】Matplotlib3 Python 数据可视化 - Matplotlib3 绘制饼状图(Pie)
java
wuminyu41 分钟前
专家视角看JVM_StartThread
java·linux·c语言·jvm·c++
awljwlj1 小时前
黑马点评复习—缓存相关【包含可能的问题和基础知识复习】
java·后端·spring·缓存
Gofarlic_OMS1 小时前
ENOVIA基于Token的许可证消费模式分析与分点策略
java·大数据·开发语言·人工智能·制造
ROLL.71 小时前
Git和Repo
java·git·安卓