package com.example.test.controller;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileNotFoundException;
public class libreOfficePDFController {
private static final Logger log = LoggerFactory.getLogger(libreOfficePDFController.class);
/**
* 将office文档转成pdf文件
* @param sourcePath
* @param targetPath
*/
@SneakyThrows
public static boolean word2pdf(String sourcePath, String targetPath) {
if (!new File(sourcePath).exists()) {
throw new FileNotFoundException();
}
// 配置环境变量 $PATH 使用如下:
// String command = String.format("soffice --convert-to pdf:writer_pdf_Export %s --outdir %s", sourcePath, targetPath);
// 未配置环境变量如下:
String command = String.format("/Applications/LibreOffice.app/Contents/MacOS/soffice --convert-to pdf:writer_pdf_Export %s --outdir %s", sourcePath, targetPath);
log.info("command=" + command);
boolean flag = executeCommand(command);
log.info("word2pdf: convert pdf complete. flag="+flag);
return flag;
}
/**
* 执行libreoffice的转换命令
* @param command
* @return
*/
public static boolean executeCommand(String command){
try {
long start = System.currentTimeMillis();
Process process = Runtime.getRuntime().exec(command);
// 返回值是子线程执行完毕的返回值,返回0表示正常结束
int exitStatus = process.waitFor();
log.info("executeCommand: convert pdf exitStatus= " + exitStatus);
// 销毁子进程
process.destroy();
long end = System.currentTimeMillis();
log.info("executeCommand: convert pdf cost time " + (end - start) + "ms");
return exitStatus == 0;
}catch (Exception e){
log.error("executeCommand: runtime exec error", e);
}
return false;
}
@SneakyThrows
public static void main(String[] args) {
String source = "/tmp/pdf/test.DOCX";
String target = "/tmp/pdf/";
boolean inputStream = word2pdf(source, target);
log.info(inputStream);
}
}