右键点击“此电脑”或“我的电脑”,选择“属性”。
点击“高级系统设置”。
在“系统属性”窗口中,点击“环境变量”按钮。
在“系统变量”区域,找到名为Path的变量并选择它,然后点击“编辑”。
在打开的窗口中,点击“新建”,然后添加wkhtmltoimage的安装路径,例如D:safewarewkhtmltopdfbin。
点击“确定”保存更改。
wkhtmltoimage --version
以下在已在window环境验证
package com.aspire.sxcrec.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class HtmlToPdfConverter {
private static String wkhtmltopdfPath = "D:\safeware\wkhtmltopdf\bin\wkhtmltopdf.exe"; // Windows
// 或
// String wkhtmltopdfPath = "/usr/local/bin/wkhtmltopdf"; // Linux/Mac
public static void main(String[] args) {
String htmlFilePath = "E:\Desktop\export12.html"; // 输入HTML文件路径
String outputPdfPath = "E:\Desktop\output.pdf"; // 输出PDF路径
try {
// 构建命令
ProcessBuilder processBuilder = new ProcessBuilder(
wkhtmltopdfPath,
htmlFilePath,
outputPdfPath
);
// 启动进程
Process process = processBuilder.start();
// 捕获错误流(wkhtmltopdf 通常将日志输出到错误流)
BufferedReader errorReader = new BufferedReader(
new InputStreamReader(process.getErrorStream())
);
String line;
while ((line = errorReader.readLine()) != null) {
System.err.println(line); // 打印错误信息
}
// 等待命令执行完成
int exitCode = process.waitFor();
if (exitCode == 0) {
System.out.println("PDF 生成成功!");
} else {
System.out.println("PDF 生成失败,错误码: " + exitCode);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
参与评论
手机查看
返回顶部