之前使用dom4j转换,依赖office;
网上还有Apache poi和itextpdf方式,尝试后发现复杂word,比如包含表格曲线等支持性不好。
最后发现 LibreOffice:不依赖office,免费,可跨平台
参考链接:
https://developer.aliyun.com/article/1629006
https://blog.csdn.net/u013984781/article/details/144430991
1、下载LibreOffice
https://zh-cn.libreoffice.org/download/libreoffice/
2、代码
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class WordToPdfConverter {
//LibreOffice的安装路径(如果环境变量已经配置,则不需要此路径)
private static final String LIBREOFFICE_PATH = "/path/to/libreoffice"; //例如: "/usr/bin/libreoffice" 或 "C:\\Program Files\\LibreOffice\\program\\soffice.exe"
public static void main(String[] args) {
String inputFilePath = "path/to/your/input.docx";
String outputFilePath = "path/to/your/output.pdf";
convertWordToPdf(inputFilePath, outputFilePath);
}
public static void convertWordToPdf(String inputFilePath, String outputFilePath) {
File inputFile = new File(inputFilePath);
File outputFile = new File(outputFilePath);
if (!inputFile.exists()) {
System.err.println("Input file does not exist: " + inputFilePath);
return;
}
// 构建LibreOffice命令行指令
StringBuilder command = new StringBuilder();
if (LIBREOFFICE_PATH != null && !LIBREOFFICE_PATH.isEmpty()) {
command.append(LIBREOFFICE_PATH).append(" --headless ");
} else {
command.append("soffice --headless ");
}
command.append("--convert-to pdf ")
.append("--outdir ").append(outputFile.getParent())
.append(" ").append(inputFilePath);
try {
// 执行系统命令
Process process = Runtime.getRuntime().exec(command.toString());
// 读取命令执行的输出和错误流(可选)
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((line = errorReader.readLine()) != null) {
System.err.println(line);
}
// 等待进程结束
int exitCode = process.waitFor();
if (exitCode == 0) {
System.out.println("Conversion successful: " + outputFilePath);
} else {
System.err.println("Conversion failed with exit code: " + exitCode);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}