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();
        }
    }
相关推荐
长不大的杨瑞杰5 分钟前
Spring AI 企业级 RAG 实战:检索、重排、结构化输出与提示注入防护
java·人工智能·spring·llm·rag·springai
阿凤2117 分钟前
学习java---流程控制篇
java·开发语言·学习
IT研究室25 分钟前
最新计算机毕业设计选题推荐-基于spring boot的房屋交易系统-网站-文档指导-Java-springboot
java·spring boot·课程设计
RuoyiOffice39 分钟前
Java物联网项目拆解:设备接入之后,数据怎样真正用起来
java·vue.js·spring boot·物联网·iot·企业管理·ruoyi office
Rain的Java大神之路1 小时前
Java后端用Vue3+TS独立闭环之后,MyBatis-Plus该退到哪一层?聊聊2026全栈效能的责任边界
java·后端·ai编程
比特屿1 小时前
Spring AI 2.1实战(六):Tool Calling全链路,从@Tool 到人工确认
java·后端
海宇服务1 小时前
零信任架构实战:基于海宇对外投资历史查询服务构建自动化供应商关联主体合规审查网关
java·人工智能·架构·自动化
我命由我123451 小时前
Android 广播 - Android 开机广播实现开机自启应用
android·java·linux·java-ee·kotlin·android studio·android-studio
stormsha2 小时前
`Could not create connection to database server`:MySQL 8 连不上,真凶藏在第 4 层
java·后端·mysql
泡海椒2 小时前
jquick-pdf 仪表盘(JChartType.Guage)实战:从一个分值到一页 PDF 的七站
pdf