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 分钟前
Java 17调用Embeddings API:余弦相似度与FAQ拒答阈值
java·开发语言·人工智能
闭包不眠9 分钟前
PDF文字提取交付前该检查什么
运维·服务器·图像处理·人工智能·计算机视觉·pdf
Q264336502343 分钟前
【有源码】基于SpringBoot+Vue的博物馆展览与服务一体化平台-java博物馆数字化展品展示与交互平台设计
java·vue.js·spring boot·spring·毕业设计·javaweb·课程设计
guo_wen_qiang1 小时前
项目使用sentinel遇到的问题
java·sentinel
CarIise1 小时前
IDEA与Maven基础课堂笔记
java·intellij-idea·caffe
小溪学编程1 小时前
C语言篇:枚举类型
java·c语言·前端
云和数据.ChenGuang1 小时前
JAVAEE AI工程师路线图
java·人工智能·java-ee·fastapi·springai·langchain4j
2601_962885721 小时前
如何用 Python 统计 A 股连续涨停(几连板)?
java·linux·python
Latchh1 小时前
PDF提取到文字后怎样发现乱码
图像处理·人工智能·计算机视觉·pdf
大圣编蚕1 小时前
Spring AOP 失效排查:从原理到实战的完整指南
java·后端·spring