package com.springboot.springboottopdf.util;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteResultHandler;
import java.util.concurrent.Semaphore;
public class PDFUtils {
public static void convert(String officePath,String outPath) throws Exception {
DefaultExecutor exec = new DefaultExecutor();
// 同步等待
Semaphore semaphore = new Semaphore(1);
semaphore.acquire();
ExecuteResultHandler erh = new ExecuteResultHandler() {
@Override
public void onProcessComplete(int i) {
semaphore.release();
//转换完成逻辑
}
@Override
public void onProcessFailed(ExecuteException e) {
semaphore.release();
//转换失败逻辑
e.printStackTrace();
}
};
String command = "cmd.exe /c soffice --invisible --convert-to pdf --outdir \""+outPath+"\" \""+officePath+"\"";
System.out.println("执行office文件转换任务,命令为" + command);
exec.execute(CommandLine.parse(command), erh);
// 等待执行完成
semaphore.acquire();
}
public static void main(String[] args) throws Exception {
convert("D:/鸿蒙笔记.doc","D:/");
}
}