最近有这么一个需求,需要将一下做好的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
这是我自己代码的包目录,如果你原版不动,就需要先建立这样的项目结构,如果是纯技术者,就无视我这句代码就好啦~