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();
        }
    }
相关推荐
逐米时代2 分钟前
远程运维诊断减少到场率
java·服务器·前端
禾小西6 分钟前
Redis AOF 日志:宕机了,如何避免数据丢失?
java·redis·mybatis
xuxigifxfh21 分钟前
HJ11 数字颠倒
java·开发语言·华为机考
wno70425 分钟前
Spring Boot整合Quartz
java·spring boot·后端
步行cgn39 分钟前
MySQL 报错:Access denied for user ‘root‘@‘localhost‘ 详解
java·数据库·spring
一个有温度的技术博主1 小时前
深拷贝和浅拷贝:一次“搬家”事故
java·后端
程序员清风2 小时前
AI时代建议学点自己真正感兴趣的!
java·后端·面试
Wang's Blog2 小时前
Java框架 SpringCloud 快速入门: Nacos 配置热更新
java·spring·spring cloud
西索斯coding2 小时前
Kimi k2.7-code-highspeed 接入 Cline 教程:baseURL 路由变更 + model_id 正确写法
java·服务器·数据库·ai
用户094248568032 小时前
第29章:【OpenJDK中级篇综合实战】百万长连接网关的JVM稳定性工程
java·jvm