Java使用Documents4j实现Word转PDF(知识点+案例)

文章目录

前言

博主介绍:✌目前全网粉丝2W+,csdn博客专家、Java领域优质创作者,博客之星、阿里云平台优质作者、专注于Java后端技术领域。

涵盖技术内容:Java后端、算法、分布式微服务、中间件、前端、运维、ROS等。

博主所有博客文件目录索引:博客目录索引(持续更新)

视频平台:b站-Coder长路


源码获取

项目源码:GiteeGithub

本篇文档的视频系列讲解:Java实现自动化pdf打水印工具 开源PDF工具PDFBoxWord、Word转PDF开源工具Documents4j


一、认识Documents4j

​ Documents4j 是一个开源的 Java 库,用于在 Java 应用程序中进行 Microsoft Office 文档(如 Word、Excel、PowerPoint 等)的转换。它利用 Microsoft Office 的本机 API,通过启动 Microsoft Office 进程来执行文档转换。Documents4j 提供了一种简单的方式来将 Office 文档转换为其他格式,例如将 Word 文档转换为 PDF、将 Excel 表格转换为 CSV 等。

​ Documents4j 的工作原理是通过将 Microsoft Office 作为外部进程启动,并与其进行通信来执行文档转换任务。这种方法使得可以利用 Microsoft Office 的强大功能来执行文档转换,同时又能够在 Java 环境中方便地进行集成和控制。

​ Documents4j 提供了一个简单的 API,使得在 Java 应用程序中执行文档转换变得简单。它支持多线程操作,并且具有一定的性能优化,使得可以高效地处理大量文档转换任务。


二、快速集成

2.1、pom.xml依赖

xml 复制代码
<!--word 2 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 2 pdf end -->

2.2、word转PDF实现

项目目录

WordUtils.java

java 复制代码
package com.changlu.utils;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import java.io.*;

public class WordUtils {

    /**
     * Word转PDF
     * @param filePath 源docx文件目录及名称  示例:C:\Users\93997\Desktop\watermark tools\watermarkTools\src\main\resources\2024-2-8计算机.docx
     * @param outFilePath 输出文件目录及名称 示例:C:\Users\93997\Desktop\watermark tools\watermarkTools\src\main\resources\2024-2-8.pdf
     */
    public static void wordToPdf(String filePath, String outFilePath) {
        //源文件地址
        File inputWord = new File(filePath);
        //导出文件地址
        File outputFile = new File(outFilePath);
        InputStream doc = null;
        OutputStream outputStream = null;
        try {
            doc = new FileInputStream(inputWord);
            outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder().build();
            //转换docx=>pdf
            boolean flag = converter.convert(doc).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
            if (flag) {
                converter.shutDown();
            }
            doc.close();
            outputStream.close();
            System.out.println("文件名:" + outFilePath + " 转换成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String filePath = "C:\\Users\\93997\\Desktop\\watermark tools\\watermarkTools\\src\\main\\resources\\2024-2-8计算机.docx";
        String outFilePath = "C:\\Users\\93997\\Desktop\\watermark tools\\watermarkTools\\src\\main\\resources\\2024-2-8.pdf";
        //word转pdf
        WordUtils.wordToPdf(filePath, outFilePath);
    }

}

Demo6.java

java 复制代码
package com.changlu.demos;

import com.changlu.utils.WordUtils;
import java.io.UnsupportedEncodingException;

/**
 * @Description: Documents4j案例:word转PDF实现
 * @Author: changlu
 * @Date: 2:18 PM
 */
public class Demo6 {
    public static void main(String[] args) throws UnsupportedEncodingException {
//        String originPath = URLDecoder.decode(Main.class.getClassLoader().getResource("input.docx").getFile(), "UTF-8"); //获取到的是target下的类目录
        String originPath = "F:\\00核心知识、成果、视频产出区\\技术视频\\2024.2.15 自制默默学打水印工具 watermark tools\\watermarkTools\\src\\main\\resources\\input.docx";
        String targetPath = originPath.replace("input.docx", "output.pdf");
        //docx转为pdf文件
        WordUtils.wordToPdf(originPath, targetPath);
    }
}

测试效果


参考文章

1\]. [不要在去充VIP啦 ,Java 实现 PDF、Word 互转](https://www.bilibili.com/video/BV1Xh4y1F7C4/?spm_id_from=333.337.search-card.all.click&vd_source=b19269a4ae00481d5ff13d1897127b8b) *** ** * ** *** ## 资料获取 大家点赞、收藏、关注、评论啦\~ 精彩专栏推荐订阅:在下方专栏👇🏻 * [长路-文章目录汇总(算法、后端Java、前端、运维技术导航)](https://blog.csdn.net/cl939974883/category_11568291.html?spm=1001.2014.3001.5482):博主所有博客导航索引汇总 * [开源项目Studio-Vue---校园工作室管理系统(含前后台,SpringBoot+Vue)](https://changlu.blog.csdn.net/article/details/125295334):博主个人独立项目,包含详细部署上线视频,已开源 * [学习与生活-专栏](https://blog.csdn.net/cl939974883/category_10700595.html):可以了解博主的学习历程 * [算法专栏](https://blog.csdn.net/cl939974883/category_11403550.html?spm=1001.2014.3001.5482):算法收录 更多博客与资料可查看👇🏻获取联系方式👇🏻,🍅文末获取开发资源及更多资源博客获取🍅 *** ** * ** *** 整理者:长路 时间:2024.2.15

相关推荐
二哈赛车手1 小时前
新人笔记---ApiFox的一些常见使用出错
java·笔记·spring
栗子~~2 小时前
JAVA - 二层缓存设计(本地缓冲+redis缓冲+广播所有本地缓冲失效) demo
java·redis·缓存
YDS8292 小时前
DeepSeek RAG&MCP + Agent智能体项目 —— RAG知识库的搭建和接口实现
java·ai·springboot·agent·rag·deepseek
未若君雅裁3 小时前
MyBatis 一级缓存、二级缓存与清理机制
java·缓存·mybatis
AI人工智能+电脑小能手3 小时前
【大白话说Java面试题 第65题】【JVM篇】第25题:谈谈对 OOM 的认识
java·开发语言·jvm
阿维的博客日记4 小时前
Nacos 为什么能让配置动态生效?(涉及 @RefreshScope 注解)
java·spring
雨辰AI4 小时前
SpringBoot3 + 人大金仓读写分离 + 分库分表 + 集群高可用 全栈实战
java·数据库·mysql·政务
辰海Coding5 小时前
MiniSpring框架学习-完成的 IoC 容器
java·spring boot·学习·架构
小小编程路5 小时前
C++ 多线程与并发
java·jvm·c++
AI视觉网奇5 小时前
linux 检索库 判断库是否支持
java·linux·服务器