Libreoffice实现Word、Excel在线预览

时间:2025-01-26 12:54:38
package com.dxy.util.excel; import java.io.File; import org.jodconverter.core.office.OfficeException; import org.jodconverter.local.JodConverter; import org.jodconverter.local.office.LocalOfficeManager; public class JodConverterDemo { public static void main(String[] args) throws OfficeException { // 获取LibreOffice服务实例 LocalOfficeManager instance = getInstance(); try { // 启动服务, 注意:如果是Spring boot项目,只需要在项目启动时 start 一次即可 instance.start(); // docx 转 pdf File srcFile1 = new File("D:\\test1.docx"); File targetFile1 = new File("D:\\test1.pdf"); JodConverter.convert(srcFile1).to(targetFile1).execute(); // ppt 转 pdf File srcFile2 = new File("D:\\test2.ppt"); File targetFile2 = new File("D:\\test2.pdf"); JodConverter.convert(srcFile2).to(targetFile2).execute(); // excel 转 html, excel 转 pdf 效果不好 File srcFile3 = new File("E:\\tmp\\user2.xlsx"); File targetFile3 = new File("E:\\tmp\\user2.html"); JodConverter.convert(srcFile3).to(targetFile3).execute(); } finally { // 停止服务,demo中需要手动停止LibreOffice服务,不然项目无法退出,只能手动杀掉LibreOffice进程 instance.stop(); } } public static LocalOfficeManager getInstance() { LocalOfficeManager.Builder builder = LocalOfficeManager.builder().install(); // 此处是 LibreOffice 的目录 builder.officeHome("C:\\Program Files\\LibreOffice"); // 指定 LibreOffice 服务的端口号,若要启动多个服务,则填写多个端口号 builder.portNumbers(2000); // 转换超时时间 builder.taskExecutionTimeout(60L * 1000); // 队列超时时间 builder.taskQueueTimeout(1000 * 60 * 60L); // 1小时 return builder.build(); } }