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();
        }
    }
相关推荐
搬山境KL攻城狮16 小时前
maven 私服上传jar
java·maven·jar
q***563816 小时前
Spring Boot--@PathVariable、@RequestParam、@RequestBody
java·spring boot·后端
FREE技术16 小时前
学生成绩管理系统 基于java+springboot+vue实现前后端分离项目并附带万字文档(源码+数据库+万字详设文档+软件包+安装教程)
java·vue.js·spring boot·mysql
q***575017 小时前
Spring Boot(七):Swagger 接口文档
java·spring boot·后端
E_ICEBLUE18 小时前
Python 教程:如何快速在 PDF 中添加水印(文字、图片)
开发语言·python·pdf
南方的狮子先生18 小时前
【C++】C++文件读写
java·开发语言·数据结构·c++·算法·1024程序员节
bemyrunningdog18 小时前
IntelliJ IDEA导出WAR包全指南
java·ide·intellij-idea
虫师c18 小时前
List vs Set:深入剖析Java两大集合的核心区别与实战应用
java·数据结构·list·set·java集合
emiya_saber18 小时前
Linux 硬盘分区管理
java·linux·网络
量子炒饭大师19 小时前
【一天一个计算机知识】—— 【编程百度】预处理指令
java·开发语言