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

相关推荐
ckhcxy2 分钟前
继承和多态(二)
java·开发语言
今天你TLE了吗4 分钟前
LeeCode Hot100随机链表的复制 java易懂题解
java·数据结构·链表
山峰哥6 分钟前
现代 C++ 的最佳实践:从语法糖到工程化思维的全维度探索
java·大数据·开发语言·数据结构·c++
CoderYanger6 分钟前
动态规划算法-两个数组的dp(含字符串数组):43.不同的子序列
java·算法·leetcode·动态规划·1024程序员节
故渊ZY7 分钟前
Spring DI核心原理:依赖注入实战全解析
java·spring
Andy工程师15 分钟前
Spring Boot 的核心目标
java·spring boot·后端
努力搬砖的咸鱼19 分钟前
API 网关:微服务的大门卫
java·大数据·微服务·云原生
小裕哥略帅28 分钟前
Springboot中全局myBaits插件配置
java·spring boot·后端
MX_935937 分钟前
Spring中Bean注入方式和注入类型
java·后端·spring
爱跑步的程序员~42 分钟前
IOC和AOP详解
java·spring