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();
        }
    }
相关推荐
codigger1 小时前
ThreadLocal 会内存泄露吗?
java·内存泄漏·threadlocal
挖掘狂人1 小时前
ThreadLocal 会内存泄露吗?
java·安全·架构
未秃头的程序猿1 小时前
给新模块加了个 @MapperScan,启动崩了,最后发现跟 MapperScan 没关系
java·后端·mybatis
SimonKing2 小时前
WorkBuddy又推出新的限免模型(Hy4 flash)了,羊毛可以薅起来了
java·后端·程序员
Rain的Java大神之路2 小时前
别再死背"三级缓存"了!拿 Spring 7.0.8 源码,把 IoC、AOP、事务、循环依赖四大深水区一次蹚平
java·后端·面试
H H.2 小时前
Java企业级开发:从框架到工程化实战
java·开发语言·经验分享·其他·课程设计
wno7042 小时前
springboot整合FastDFS
java·spring boot·后端
顧棟3 小时前
组件生命周期设计:从硬编码初始化到状态机
java·ide
特立独行的猫A10 小时前
别再用 nohup 了:让应用在后台常驻的正确姿势与 systemd 服务详解
java·后端·python
一起_java11 小时前
技术文章-基于Dify-Agent的智能问答系统设计与实现
java·spring boot·后端·agent·dify