之前使用过,好长时间不用,忘记了,耽误了半天,记录下来,方便自己,方便他人
示例代码
private static void genPdf(String url,String pdfFilePath) throws IOException {
String osName = System.getProperty("os.name").toUpperCase();
log.info("osName:{}",osName);
if(osName.contains("")){
}
List<String> pdfCommand = Arrays.asList(
/*安装程序路径的bin文件夹下*/
/*"chrome.exe --no-pdf-header-footer --headless --disable-gpu --no-sandbox --print-to-pdf="+pdfFilePath+" " +url*/
"/usr/bin/google-chrome",
"--no-pdf-header-footer",
"--headless",
"--disable-gpu",
"--no-sandbox",
"--print-to-pdf="+pdfFilePath,
url
);
for (int i = 0; i < pdfCommand.size(); i++) {
String command = pdfCommand.get(i);
log.info("command:{}",command);
}
ProcessBuilder pb = new ProcessBuilder(pdfCommand);
Process pdfProcess;
int status;
try {
pdfProcess = pb.start();
try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(pdfProcess.getInputStream(), StandardCharsets.UTF_8))){
while (pdfProcess.isAlive()) {
while (bufferedReader.ready()) {
String line = bufferedReader.readLine();
log.info("line:{}",line);
}
}
status = pdfProcess.waitFor();
}catch (InterruptedException e) {
throw new RuntimeException("PDF generation failed");
}
//检测是否生成成功,如果成功则创建下载pdf的路径
if(status==0) {
log.info("生成pdf成功");
}
}
catch (IOException ex) {
ex.printStackTrace();
log.info("ex:{}",ex.getCause());
throw new RuntimeException("PDF转化失败");
}
}
注意事项:
注意事项1:软件一定要写绝对路径,配置了环境变量也不行;配置了环境变量只是保证在黑窗口不用输入绝对地址,但是java调用不行,必须输入绝对路径
注意事项2:多个参数,一个参数一行命令,且首尾不能有空格