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();
        }
    }
相关推荐
SEO-狼术5 分钟前
All-About-PDF provides DRM
pdf
希望永不加班14 分钟前
SpringBoot 定时任务:@Scheduled 基础与动态定时
java·spring boot·后端·spring
派大星酷14 分钟前
跨域是什么 有什么影响 怎么解决
java·网络
CV艺术家14 分钟前
mysql数据迁移到达梦数据库
java·数据库
wuqingshun31415916 分钟前
说一下mybatis里面#{}和${}的区别
java·spring·mybatis
SimonKing19 分钟前
每天白送4000万Token!这款“龙虾”AI神器,微信就能操控电脑
java·后端·程序员
橘子编程24 分钟前
编程语言全指南:从C到Rust
java·c语言·开发语言·c++·python·rust·c#
艾莉丝努力练剑26 分钟前
【Linux线程】Linux系统多线程(三):Linux线程 VS 进程,线程控制
java·linux·运维·服务器·c++·学习·ubuntu
小白天下第一35 分钟前
java+三角测量(两个工业级)+人体3d骨骼关键点获取(yolov8+HRNET_w48_2d)
java·yolo·3d·三角测量
William Dawson44 分钟前
Java 后端高频 20 题超详细解析 ①
java·开发语言