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();
        }
    }
相关推荐
Cat_Rocky5 分钟前
通过k8s实现单pod部署
java·容器·kubernetes
秋918 分钟前
Java AI编程工具全景解析:功能、收费与工单系统实战指南
java·开发语言·ai编程
瑶山18 分钟前
IDEA 配置Go语言开发环境、GOPATH传统 Go 项目导入
java·golang·intellij-idea
weixin_4196583134 分钟前
RabbitMQ 的高级特性
java·分布式·rabbitmq
白晨并不是很能熬夜35 分钟前
【RPC】第 1 篇:全景篇 — 一次 RPC 调用的完整旅程
java·网络·后端·网络协议·面试·rpc·java-zookeeper
民乐团扒谱机1 小时前
【附完整代码】Python爬取古筝网曲谱图片一键生成PDF(下·PDF生成与GUI篇)
开发语言·python·pdf
z小天才b1 小时前
Java 设计模式完全指南:从入门到精通
java·开发语言·设计模式
玛卡巴卡ldf1 小时前
【Springboot9】将业务模块数据导出为PDF
pdf·springboot
烤麻辣烫1 小时前
算法--二分搜索
java·开发语言·学习·算法·intellij-idea
逍遥德1 小时前
MQTT教程详解-03. 高级知识点
java·物联网·中间件·信息与通信·iot·iotdb