java把word转pdf使用jar包maven依赖

引入maven

java 复制代码
 <!--word转pdf-->
 <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>
java 复制代码
package org.springblade.modules.api.utils;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import org.springblade.core.tool.utils.Func;


import java.io.*;

public class ExportWordToPdfUtil {

    /**
     * Word转PDF
     *
     * @param filePath    源docx文件目录及名称  示例:F:\\machine\\naReport\\20251022\\1761112860572运行情况简报.docx
     * @param outFilePath 输出文件目录及名称 示例:F:\\machine\\naReport\\20251022\\1761112860572运行情况简报.pdf
     */
    public static void wordToPdf(String filePath, String outFilePath) {
        //NaReport naReport = new NaReport();
        File inputWord = new File(filePath);
        File outputFile = new File(outFilePath);

        // 确保输出目录存在
        File parentDir = outputFile.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs();
        }

        // 如果输出文件已存在则删除(实现替换)
        if (outputFile.exists()) {
            if (!outputFile.delete()) {
                System.err.println("警告:无法删除已存在的文件,可能被占用或无权限: " + outFilePath);
            }
        }

        IConverter converter = null;
        try (InputStream doc = new FileInputStream(inputWord);
             OutputStream outputStream = new FileOutputStream(outputFile)) {

            converter = LocalConverter.builder().build();
            boolean flag = converter.convert(doc)
                    .as(DocumentType.DOCX)  // 修正为DOCX(原代码误用DOC)
                    .to(outputStream)
                    .as(DocumentType.PDF)
                    .execute();

            if (flag) {
                // 获取文件大小和绝对路径
                long fileSize = outputFile.length();
                //naReport.setSize(smartConvert(fileSize));
                //naReport.setUrl(outFilePath);
                System.out.println("文件大小:" + smartConvert(fileSize));
                System.out.println("文件名:" + outFilePath + " 转换成功!");
                // TODO返回格式:文件大小|绝对路径,我这里是为了自己处理,不需要的可以直接删除
                //return naReport;
            } else {
                System.err.println("转换失败,未知错误");
            }
        } catch (Exception e) {
            // 转换失败时删除可能生成的不完整文件
            if (outputFile.exists()) {
                outputFile.delete();
            }
            e.printStackTrace();
        } finally {
            // 确保无论成功与否都关闭转换器
            if (converter != null) {
                converter.shutDown();
            }
        }
    }

    /**
     * 将字节大小转换为易读的字符串(自动选择最佳单位)
     *
     * @param bytes 文件大小(字节)
     * @return 格式化后的字符串(如:1.23 MB)
     */
    public static String formatFileSize(long bytes) {
        if (bytes < 1024) {
            return bytes + " B";
        }

        double size = bytes;
        String[] units = {"KB", "MB", "GB", "TB"};
        int unitIndex = -1;

        while (size >= 1024 && unitIndex < units.length - 1) {
            size /= 1024;
            unitIndex++;
        }

        return String.format("%.2f %s", size, units[unitIndex]);
    }

    /**
     * 转换为KB(保留两位小数)
     *
     * @param bytes 文件大小(字节)
     * @return KB大小的字符串表示
     */
    public static String toKB(long bytes) {
        double kb = bytes / 1024.0;
        return String.format("%.2f KB", kb);
    }

    /**
     * 转换为MB(保留两位小数)
     *
     * @param bytes 文件大小(字节)
     * @return MB大小的字符串表示
     */
    public static String toMB(long bytes) {
        double mb = bytes / (1024.0 * 1024.0);
        return String.format("%.2f MB", mb);
    }

    /**
     * 智能转换(自动选择KB或MB)
     *
     * @param bytes 文件大小(字节)
     * @return 最合适的单位表示
     */
    public static String smartConvert(long bytes) {
        if (bytes < 1024 * 1024) { // 小于1MB
            return toKB(bytes);
        } else {
            return toMB(bytes);
        }
    }

    public static void main(String[] args) {
        String filePath = "F:\\machine\\naReport\\20251022\\1761112860572运行情况简报.docx";
        String outFilePath = "F:/machine/naReport/20251022/1761112860572运行情况简报.pdf";
        wordToPdf(filePath, outFilePath);
    }
}
相关推荐
FQNmxDG4S20 小时前
Java多线程编程:Thread与Runnable的并发控制
java·开发语言
虹科网络安全21 小时前
艾体宝干货|数据复制详解:类型、原理与适用场景
java·开发语言·数据库
axng pmje1 天前
Java语法进阶
java·开发语言·jvm
rKWP8gKv71 天前
Java微服务性能监控:Prometheus与Grafana集成方案
java·微服务·prometheus
老前端的功夫1 天前
【Java从入门到入土】28:Stream API:告别for循环的新时代
java·开发语言·python
qq_435287921 天前
第9章 夸父逐日与后羿射日:死循环与进程终止?十个太阳同时值班的并行冲突
java·开发语言·git·死循环·进程终止·并行冲突·夸父逐日
小江的记录本1 天前
【Kafka核心】架构模型:Producer、Broker、Consumer、Consumer Group、Topic、Partition、Replica
java·数据库·分布式·后端·搜索引擎·架构·kafka
yaoxin5211231 天前
397. Java 文件操作基础 - 创建常规文件与临时文件
java·开发语言·python
极客先躯1 天前
高级java每日一道面试题-2025年11月24日-容器与虚拟化题[Dockerj]-runc 的作用是什么?
java·oci 的命令行工具·最小可用·无守护进程·完全标准·创建容器的核心流程·runc 核心职责思维导图
用户60648767188961 天前
AI 抢不走的技能:用 Claude API 构建自动化工作流实战
java