采用libreoffice将word、excel等文件转换为pdf格式
一、安装LibreOffice
LibreOffice官网下载链接(https://downloadarchive.documentfoundation.org/libreoffice/),下载对应系统的libreoffice后,按照步骤安装即可。
(注:在某项目中,采用libreoffice转码office文件为浏览器可预览文件时,libreoffice安装完成、环境配置后,服务器依旧不能访问libreoffice进行转码,此时将libreoffice的版本更换为LIbreOffice_25.2.5.2就可以了,应该是系统不兼容导致的,如遇同样的问题,可以切换版本试试)
安装完成后检查program文件夹中是否存在soffice.exe文件。
二、代码实现
代码中采用ProcessBuilder调用soffice.exe。
//其中的sofficePath安装路径下的programme文件夹中的soffice.exe
//示例:D:/Libreoffice/program/soffice.exeProcessBuilder pb = new ProcessBuilder(sofficePath,"--headless","--convert-to", "pdf","--outdir", outputDir.getAbsolutePath(),wordFile.getAbsolutePath());pb.inheritIO();Process process = pb.start();int exitCode = process.waitFor();if (exitCode != 0) {throw new RuntimeException("LibreOffice 转换失败,exitCode=" + exitCode);}
以上的转换方式时间比较慢、存在并发限制及一定的资源消耗,高并发的可以采用LibreOffice 服务模式(UNO Server)。