使用场景:为用户生成成长报告(使用Thymeleaf模版引擎技术),在PC端展示并且可以存储为PDF格式,把存储好的文件放到阿里云上。
package cn.bjsytx.phsh.evaluation.utils;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class ReportUtil {
public static void generPdf(Long tempId, Long userId, Long projectId, Long roundId) {
String osName = System.getProperty("os.name").toLowerCase();
String fileName = roundId + "_" + userId + ".pdf";
if (osName.contains("windows")) {
System.out.println("当前操作系统是 Windows");
try {
// 指定工作目录
String workingDirectory = "C:\\Program Files\\Google\\Chrome\\Application";
// 创建ProcessBuilder对象
ProcessBuilder processBuilder = new ProcessBuilder();
// 设置工作目录
processBuilder.directory(new File(workingDirectory));
// 要检查的文件夹路径
String folderPath = "E:\\generPdf";
// 创建File对象
File folder = new File(folderPath);
// 检查文件夹是否存在
if (!folder.exists()) {
// 如果文件夹不存在,尝试创建它
folder.mkdirs();
}
// 添加命令
processBuilder.command("cmd.exe", "/c", "chrome", "--headless", "--disable-gpu", "--kiosk-printing", "--no-print-header-footer", "--print-to-pdf=E:\\generPdf\\" + fileName + "", "http://127.0.0.1:5050/?tempId=" + tempId + "^&userId=" + userId + "^&projectId=" + projectId + "^&roundId=" + roundId + "");
// 启动进程
Process process = processBuilder.start();
// 等待命令执行完成
process.waitFor();
// 输出命令执行结果
int exitCode = process.exitValue();
if (exitCode == 0) {
System.out.println("Chrome command executed successfully.");
} else {
System.out.println("Chrome command failed with exit code: " + exitCode);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
} else if (osName.contains("linux")) {
System.out.println("当前操作系统是 Linux");
List<String> command = Arrays.asList(
"google-chrome",
"--headless",
"--disable-gpu",
"--print-to-pdf=/opt/"+fileName+"",
"http://127.0.0.1:5050/?tempId=" + tempId + "^&userId=" + userId + "^&projectId=" + projectId + "^&roundId=" + roundId + ""
);
// 要检查的目录路径
String directoryPath = "/opt/generPdf";
// 创建File对象
File directory = new File(directoryPath);
// 检查目录是否存在
if (!directory.exists()) {
// 如果目录不存在,尝试创建它
directory.mkdirs();
}
// 创建 ProcessBuilder 对象
ProcessBuilder processBuilder = new ProcessBuilder(command);
try {
// 启动进程并执行命令
Process process = processBuilder.start();
// 等待进程执行完成
int exitCode = process.waitFor();
if (exitCode == 0) {
System.out.println("PDF文件已成功生成");
} else {
System.out.println("生成PDF文件时出现错误");
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
生成的PDF文件上方和下方会出现时间与也页面链接多余的内容,可以在CSS样式中添加如下代码
<style type="text/css">
@page { margin: 0; }
@page:first { margin-top: 0; }
@page:first { margin-bottom: 0; }
@page { size: auto; }
</style>