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();
        }
    }
相关推荐
喝凉白开都长肉的大胖子35 分钟前
比较 main.tex 的两个不同版本(例如旧版和新版),并生成一个带有修改标记(如删除线、高亮、修订注释)的 PDF 或文本输出。
pdf·latex
white-persist38 分钟前
汇编代码详细解释:汇编语言如何转化为对应的C语言,怎么转化为对应的C代码?
java·c语言·前端·网络·汇编·安全·网络安全
程序员阿达1 小时前
开题报告之基于SpringBoot框架的图书借阅系统的设计与实现
java·spring boot·后端
Eoch771 小时前
吃透 Java 核心技术:JVM 调优、并发安全、微服务开发,解决 90% 企业级场景问题
java·后端
_处女座程序员的日常1 小时前
如何预览常见格式word、excel、ppt、图片等格式的文档
前端·javascript·word·excel·开源软件
weixin_441003641 小时前
2025教资面试真题电子版|科目试讲+结构化真题解析|完整PDF
面试·职场和发展·pdf
小兜全糖(xdqt)1 小时前
python ppt转pdf以及图片提取
python·pdf·powerpoint
番石榴AI1 小时前
视频转ppt/pdf V2.0版(新增转为可编辑PPT功能)
人工智能·pdf·powerpoint
yaoxin5211231 小时前
229. Java 集合 - 操作集合中的多个元素(批量操作)
java·开发语言·python
C++chaofan1 小时前
MyBatis - Plus学习笔记
java·spring boot·笔记·后端·mysql·架构·mybatis