用LibreOffice实现批量将pptx文件转换为pdf文件

最近有这么一个需求,需要将一下做好的ppt课件转换为pdf文件,通过LibreOffice,利用java语言,可以很好的实现该项需求,现分享如下:

首先你需要安装LibreOffice,建议从 LibreOffice官网 下载并安装适合你操作系统的版本。

如果你嫌麻烦的话,也可以直接使用我下载的这个版本:

通过网盘分享的文件:LibreOffice_25.8.4_Win_x86-64

链接: https://pan.baidu.com/s/1CRl2w-5DuEsa-Bo5J8X7nw?pwd=t2hq 提取码: t2hq

--来自百度网盘超级会员v5的分享

下载之后就傻瓜式安装就可以了。安装好之后就可以编写你的代码了,主要涉及到两个类

①ConfigLoader:

java 复制代码
package hll.hlla;

import java.io.*;
import java.util.Properties;

public class ConfigLoader {
    private static Properties props = new Properties();
    
    static {
        loadConfig();
    }
    
    private static void loadConfig() {
        // 尝试从多种位置加载配置文件
        String[] possiblePaths = {
            "./config.properties",                  // 当前工作目录
            "src/main/resources/config.properties", // Maven标准资源目录
            "config.properties"                     // 类路径根目录
        };
        
        InputStream input = null;
        for (String path : possiblePaths) {
            try {
                File file = new File(path);
                if (file.exists()) {
                    input = new FileInputStream(file);
                    System.out.println("加载配置文件: " + file.getAbsolutePath());
                    break;
                }
            } catch (FileNotFoundException e) {
                // 继续尝试下一个路径
            }
        }
        
        // 如果文件系统未找到,尝试从类路径加载(Jar包内)
        if (input == null) {
            input = ConfigLoader.class.getClassLoader()
                   .getResourceAsStream("config.properties");
            if (input != null) {
                System.out.println("从类路径加载配置文件");
            }
        }
        
        if (input != null) {
            try {
                props.load(new InputStreamReader(input, "UTF-8")); // 支持中文路径
                input.close();
            } catch (IOException e) {
                System.err.println("配置文件加载失败: " + e.getMessage());
                setDefaultValues(); // 加载失败时使用默认值
            }
        } else {
            System.err.println("未找到配置文件,使用默认值");
            setDefaultValues();
        }
    }
    
    private static void setDefaultValues() {
        // 设置默认值,防止程序崩溃
        props.setProperty("input.dir", "./ppt_input");
        props.setProperty("output.dir", "./pdf_output");
        props.setProperty("libreoffice.path", 
            "D:/Program Files/LibreOffice/program/soffice.exe");
        props.setProperty("timeout.minutes", "10");
    }
    
    public static String getInputDir() {
        return props.getProperty("input.dir");
    }
    
    public static String getOutputDir() {
        return props.getProperty("output.dir");
    }
    
    public static String getLibreOfficePath() {
        return props.getProperty("libreoffice.path");
    }
    
    public static int getTimeoutMinutes() {
        try {
            return Integer.parseInt(props.getProperty("timeout.minutes"));
        } catch (NumberFormatException e) {
            return 10; // 默认10分钟
        }
    }
    
    // 可选:热重载配置(运行时修改配置文件后重新加载)
    public static void reloadConfig() {
        props.clear();
        loadConfig();
    }
}

LibreOfficePptxToPdf:

java 复制代码
package hll.hlla;

import java.io.*;
import java.util.concurrent.TimeUnit;
import java.nio.charset.StandardCharsets; // 如果使用StandardCharsets,需要导入


public class LibreOfficePptxToPdf {
    
    /**
     * 使用LibreOffice将PPTX转换为PDF
     * 需要先安装LibreOffice:https://www.libreoffice.org/
     */
	public static boolean convertWithLibreOffice(String inputPath, String outputPath) {
        // 修改:使用配置文件中的LibreOffice路径
        String libreOfficePath = ConfigLoader.getLibreOfficePath();
        int timeoutMinutes = ConfigLoader.getTimeoutMinutes();
	    // 1. 明确指定命令各部分,避免依赖shell解析
	    String[] command = {
	    		libreOfficePath,
	        "--headless",
	        "--convert-to", "pdf",
	        inputPath, // 输入文件路径
	        "--outdir", outputPath // 输出目录路径
	    };
	    
	    // 打印检查命令(可选)
	    System.out.println("执行命令: " + String.join(" ", command));
	    
	    try {
	        ProcessBuilder processBuilder = new ProcessBuilder(command);
	        // 2. 关键:重定向错误流,以便捕获输出
	        processBuilder.redirectErrorStream(true);
	        
	        Process process = processBuilder.start();
	        
	        // 3. 捕获并打印进程输出(非常重要!)
	        try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
	            String line;
	            while ((line = reader.readLine()) != null) {
	                System.out.println("[LibreOffice输出] " + line);
	            }
	        }
	        
	        // 4. 等待完成,设置合理超时(例如10分钟)
	        boolean finished = process.waitFor(timeoutMinutes, TimeUnit.MINUTES);
	        
	        if (finished) {
	            int exitCode = process.exitValue();
	            if (exitCode == 0) {
	                System.out.println("转换成功: " + inputPath);
	                return true;
	            } else {
	                System.err.println("转换失败,退出代码: " + exitCode + ", 文件: " + inputPath);
	                return false;
	            }
	        } else {
	            process.destroyForcibly();
	            System.err.println("转换超时: " + inputPath);
	            return false;
	        }
	        
	    } catch (IOException | InterruptedException e) {
	        System.err.println("执行命令时出错 (" + inputPath + "): " + e.getMessage());
	        return false;
	    }
	}
    
    /**
     * 批量转换
     */
    public static void batchConvertWithLibreOffice(String inputDir, String outputDir) {
        File dir = new File(inputDir);
        File[] pptxFiles = dir.listFiles((d, name) -> 
            name.toLowerCase().endsWith(".pptx"));
        
        if (pptxFiles == null) {
            System.out.println("目录为空或不存在");
            return;
        }
        
        // 创建输出目录
        File outputDirFile = new File(outputDir);
        if (!outputDirFile.exists()) {
            outputDirFile.mkdirs();
        }
        
        System.out.println("开始批量转换 " + pptxFiles.length + " 个文件...");
        
        int successCount = 0;
        for (File pptxFile : pptxFiles) {
            if (convertWithLibreOffice(pptxFile.getAbsolutePath(), outputDir)) {
                successCount++;
            }
        }
        
        System.out.println("转换完成!成功: " + successCount + "/" + pptxFiles.length);
    }
    
    public static void main(String[] args) {
        // 从配置文件读取路径
        String inputDir = ConfigLoader.getInputDir();
        String outputDir = ConfigLoader.getOutputDir();
        
        System.out.println("输入目录: " + inputDir);
        System.out.println("输出目录: " + outputDir);
        System.out.println("超时设置: " + ConfigLoader.getTimeoutMinutes() + "分钟");
        
        // 执行批量转换
        batchConvertWithLibreOffice(inputDir, outputDir);
    }
}

另外还需要一个配置文件config.properties

XML 复制代码
# PPTX文件所在的输入目录
input.dir=E:/src/ppt_input
# PDF输出的目标目录
output.dir=E:/src/pdf_output

# 可选:LibreOffice安装路径(应对路径变化)
libreoffice.path=D:/Program Files/LibreOffice/program/soffice.exe
# 可选:转换超时时间(分钟)
timeout.minutes=10

这个配置文件和你的src目录放在同级就可以了,其中的input.dir是你要转换的pptx文件所在的目录,output.dir是你转换后的pdf文件要保存的目录,libreoffice.path是你安装libreoffice后soffice.exe所在的目录,我是放在D盘了,你如果没有修改安装路径,大概率是C:/Program Files/LibreOffice/program/soffice.exe。

准备工作就是这么多,至此你就可以拥有一个免费的可以批量将pptx转换成pdf文件的工具了!

要是你对此感兴趣,快去尝试一下吧!

当然如果你是纯小白的话,要注意一下代码开头的这句话:

package hll.hlla

这是我自己代码的包目录,如果你原版不动,就需要先建立这样的项目结构,如果是纯技术者,就无视我这句代码就好啦~

相关推荐
鱼蛋-Felix2 小时前
C#浮点数在部分国家解析失效问题
开发语言·unity·c#
冰暮流星2 小时前
javascript数据类型转换-转换为数字型
开发语言·前端·javascript
4***17542 小时前
Python 小游戏实战:打造视觉精美的数独小游戏
开发语言·python·pygame
3***g2052 小时前
MATLAB高效算法设计原则利用MATLAB内置函数
开发语言·算法·matlab
知秋正在9962 小时前
Java实现Html保存为.mhtml文件
java·开发语言·html
q***44152 小时前
Java性能优化实战技术文章大纲Java性能优化的核心目标与原则
java·开发语言·性能优化
csbysj20202 小时前
Ruby CGI Session
开发语言
lly2024062 小时前
NumPy 迭代数组
开发语言
rgeshfgreh2 小时前
Python闭包:函数记住状态的秘密
开发语言·python