首先 下载libreoffice
并配置环境变量
地址-> https://zh-cn.libreoffice.org/
package cn.com.toyota.sales.dist.scd.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
/******************************************************** <BR>
* Class名 Excle2PDF <BR>
* 机能概要: Excel 另存为 PDF <BR>
* 调用libreoffice另存 需要安装libreoffice <BR>
********************************************************/
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)