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();
        }
    }
相关推荐
brave_zhao5 小时前
如何解决 Spoon 与 Carte 互联的 UTF-8 编码问题
java
切糕师学AI5 小时前
轻量pdf阅读器推荐
pdf
重生之我是Java开发战士5 小时前
【数据结构】Map、Set与哈希表底层原理
java·数据结构·散列表
L.EscaRC5 小时前
深度解析 Spring 框架核心代理组件 MethodProxy.java
java·开发语言·spring
拽着尾巴的鱼儿5 小时前
Spring 缓存 @Cacheable 实现原理
java·spring·缓存
dabidai5 小时前
JSR-250JavaEE规范
java
Jackson@ML5 小时前
2026最新版IntelliJ IDEA安装使用指南
java·ide·intellij-idea
逍遥德5 小时前
函数式编程 Java Lambda Stream及其实现类常用函数
java·后端·spring
2501_941982055 小时前
Java 分布式环境下的 Access_Token 一致性方案:如何避免多节点冲突?
java·开发语言·分布式
一个无名的炼丹师5 小时前
DeepSeek+LangGraph构建企业级多模态RAG:从PDF复杂解析到Agentic智能检索全流程实战
python·pdf·大模型·多模态·rag