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();
        }
    }
相关推荐
tuokuac20 分钟前
java中的浮点数基本操作
java·开发语言
源码技术栈43 分钟前
springboot支持多家机构共同使用的java门诊信息管理系统源码
java·源码·诊所·医保·门诊管理·医生工作站·处方
Empty_77743 分钟前
K8S-Job & Cronjob
java·linux·docker·容器·kubernetes
AI云原生1 小时前
在 openEuler 上使用 x86_64 环境编译 ARM64 应用的完整实践
java·运维·开发语言·jvm·开源·开源软件·开源协议
科普瑞传感仪器1 小时前
航空航天制造升级:机器人高精度力控打磨如何赋能复合材料加工?
java·前端·人工智能·机器人·无人机·制造
q_19132846952 小时前
基于SpringBoot2+Vue2的宠物上门服务在线平台
java·vue.js·spring boot·mysql·宠物·计算机毕业设计·源码分享
CoderYanger2 小时前
动态规划算法-两个数组的dp(含字符串数组):42.不相交的线
java·算法·leetcode·动态规划·1024程序员节
小蝙蝠侠2 小时前
async-profiler 火焰图宽度是否可信?哪些情况下会误导?(深度解析)
java·性能优化
IT_Octopus2 小时前
java多线程环境下 安全地初始化缓存(避免缓存击穿),同时兼顾性能 的双重检查锁方案
java·spring·缓存