JAVA 实现Excel 转换PDF(开源) 且效果较好的版本


JAVA 实现Excel 转换PDF(开源) 且效果较好的版本 
首先 下载libreoffice 并配置环境变量 
地址-> https://zh-cn.libreoffice.org/
JAVA代码如下

查看代码

package cn.com.toyota.sales.dist.scd.utils;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;


/******************************************************** 
* Class名 Excle2PDF
* 机能概要: Excel 另存为 PDF
* 调用libreoffice另存 需要安装libreoffice
********************************************************/ public class Excle2PDF { private static final Logger logger = LoggerFactory.getLogger(Excle2PDF.class); /** * 另存为PDF * @param filePath 文件全路径 * @param outPath 输出路径 * @return */ public static void save2PDF (String filePath , String outPath) { long start = System.currentTimeMillis(); logger.info("start:{} ms", start); String command = ""; String osName = System.getProperty("os.name"); if (osName.contains("Windows")) { command = "soffice --headless --convert-to pdf "+ "d:" + filePath + " --outdir " + "d:" + outPath; exec(command,filePath); }else { command = "libreoffice7.2 --headless --invisible --convert-to pdf " +filePath + " --outdir " +outPath; exec(command,filePath); // filePath.replace("excel", "pdf"); // filePath.replace(".xlsx", ".pdf"); // File file = new File( filePath); // while (!file.exists()) { // System.out.println("文件出错 正在重新生成 = " + filePath); // exec(command, filePath); // } } long end = System.currentTimeMillis(); logger.info("end:{} ms", end); logger.info("用时:{} ms", end - start); } public static boolean exec(String command, String filePath) { Process process;// Process可以控制该子进程的执行或获取该子进程的信息 try { process = Runtime.getRuntime().exec(command);// exec()方法指示Java虚拟机创建一个子进程执行指定的可执行程序,并返回与该子进程对应的Process对象实例。 // 下面两个可以获取输入输出流 InputStream errorStream = process.getErrorStream(); InputStream inputStream = process.getInputStream(); } catch (IOException e) { logger.error(" exec {} error", command, e); return false; } int exitStatus = -1; try { exitStatus = process.waitFor();// 等待子进程完成再往下执行,返回值是子线程执行完毕的返回值,返回0表示正常结束 } catch (InterruptedException e) { logger.error("InterruptedException exec {}", command, e); return false; } if (exitStatus != 0) { logger.error("exec cmd exitStatus error{} " +command, exitStatus); logger.error("生成错误的pdf " +filePath); process.destroy(); // 销毁子进程 process = null; } else { logger.info("exec cmd exitStatus sucess{} "+command, exitStatus); } process.destroy(); // 销毁子进程 process = null; return true; } }