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

相关推荐
小小深17 分钟前
了解JVM
java·jvm
Sunlight_77723 分钟前
第五章 SQLite数据库:1、SQLite 基础语法及使用案例
java·linux·服务器·jvm·数据库·tcp/ip·sqlite
JhonKI33 分钟前
【从零实现高并发内存池】内存池整体框架设计 及 thread cache实现
java·redis·缓存
何似在人间57540 分钟前
SpringAI+DeepSeek大模型应用开发——4 对话机器人
java·机器人·大模型应用开发·spring ai
-曾牛1 小时前
【LangChain4j快速入门】5分钟用Java玩转GPT-4o-mini,Spring Boot整合实战!| 附源码
java·开发语言·人工智能·spring boot·ai·chatgpt
kfepiza1 小时前
HttpSessionListener 的用法笔记250417
java·笔记·servlet·tomcat
冬天vs不冷1 小时前
SpringBoot条件注解全解析:核心作用与使用场景详解
java·spring boot·python
百锦再2 小时前
Android Studio 实现自定义全局悬浮按钮
android·java·ide·app·android studio·安卓
百锦再2 小时前
Android Studio 项目文件夹结构详解
android·java·ide·ios·app·android studio·idea
阿达King哥2 小时前
Java虚拟机(JVM)平台无关?相关?
java·jvm