// 历史版本地址 downloadarchive.documentfoundation.org/libreoffice/old/ // 最新版本地址 zh-cn.libreoffice.org/download/libreoffice/ // 国内镜像地址 mirrors.cloud.tencent.com/libreoffice/libreoffice/stable/ // 建议使用最新版安装方式
-
windows下安装
一路默认安装即可,自定义安装时切忌不要安装在中文目录下 安装成功后,可以配置环境变量,方便java程序调用
-
linux下安装
# 验证之前有没有安装过 libreoffice --version # 有安装进行卸载,没有直接下一步 yum remove libreoffice-* # 解压安装 tar -zxvf LibreOffice_7.3.3_Linux_x86-64_rpm.tar.gz cd /opt/LibreOffice_7.3.3_Linux_x86-64_rpm/RPMS # 安装*.rpm yum -y localinstall *.rpm # 安装libreoffice-headless yum install -y libreoffice-headless # 检验是否安装完成 libreoffice7.3 --version # 测试Word转PDF并安装libreoffice-writer [root@bogon Public]# libreoffice --headless --convert-to pdf 123.docx Error: source file could not be loaded # 报这个错,表示缺少writer,需要安装 yum install libreoffice-writer # 转换格式说明 libreoffice --headless --convert-to pdf {文档路径} --outdir {导出目录路径}
- 通过jodconverter调用,特点是屏蔽了具体的命令细节,直接调用convert方法即可,并且是同步返回结果或者异常;
- 通过命令调用,特点是需要自己拼接命令以及是异步返回结果;
// pom 依赖Command// 伪代码 public static boolean convertOffice2PDFSyncIsSuccess(File sourceFile, File targetFile) { try { LocalOfficeManager.Builder builder = LocalOfficeManager.builder(); builder.officeHome("C:\Program Files\LibreOffice"); builder.portNumbers(8100); builder.taskExecutionTimeout(5 * 1000 * 60); // minute builder.taskQueueTimeout(1 * 1000 * 60 * 60); // hour OfficeManager build = builder.build(); build.start(); LocalConverter make = LocalConverter.make(build); make.convert(sourceFile).to(targetFile).execute(); build.stop(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } org.jodconverter jodconverter-core 4.2.0
public static int convertOffice2PDFAsync(String filePath, String fileName, String targetFilePath) throws Exception {
String command;
int exitStatus;
String osName = System.getProperty("os.name");
String outDir = targetFilePath.length() > 0 ? " --outdir " + targetFilePath : "";
if (osName.contains("Windows")) {
command = "cmd /c cd /d " + filePath + " && start soffice --headless --invisible --convert-to pdf ./" + fileName + outDir;
} else {
command = "libreoffice6.3 --headless --invisible --convert-to pdf:writer_pdf_Export " + filePath + fileName + outDir;
}
exitStatus = executeOSCommand(command);
return exitStatus;
}
private static int executeOSCommand(String command) throws Exception {
Process process;
process = Runtime.getRuntime().exec(command); // 转换需要时间,比如一个 3M 左右的文档大概需要 8 秒左右,但实际测试时,并不会等转换结束才执行下一行代码,而是把执行指令发送出去后就立即执行下一行代码了。
int exitStatus = process.waitFor();
if (exitStatus == 0) {
exitStatus = process.exitValue();
}
// 销毁子进程
process.destroy();
return exitStatus;
}



