采用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.exe

ProcessBuilder 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)。

相关推荐
CodeCraft Studio3 小时前
国产化Word处理组件Spire.DOC教程:使用Python将文件自动化批量附加到 Word文档
python·自动化·word·spire.doc·文档自动化·word文档中添加附件·文档批量处理
东方佑3 小时前
使用Python实现Word文档与JSON格式双向转换:完整教程与代码解析
python·json·word
wtsolutions4 小时前
Sheet-to-Doc: Automate Document Generation with Excel Data and Word Templates
word·excel·wtsolutions
jayson.h5 小时前
word宏批量插入.csv格式的附件
windows·word
大卡拉米5 小时前
前端组件库 PDF、word、Excel预览
前端·pdf·word
dagouaofei1 天前
全面整理6款文档生成PPT工具,PDF转PPT不再难
python·pdf·powerpoint
yesyesyoucan1 天前
PDF全能处理站:压缩、拆分、合并一站式解决方案与核心技术解析
pdf
sunon_1 天前
解决linux系统PDF中文乱码问题
linux·运维·pdf
m5655bj1 天前
使用 C# 设置 Word 段落对齐样式
开发语言·c#·word
小灰灰搞电子1 天前
Qt PDF模块详解
数据库·qt·pdf