关于html转PDF的方法(wkhtmltopdf)
windows需要用到的工具
工具下载地址:https://wkhtmltopdf.org/downloads.html
private static String toPdfTool = "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
private static String toPdfTool = "/usr/local/bin/wkhtmltopdf";
* html转pdf
* @param htmlPath html路径,可以是本地html的路径,也可以是网络上html的路径
* @param pdfPath pdf保存路径
* @return 转换成功返回true
*/
public static boolean transPdf(String htmlPath, String pdfPath) {
File file = new File(pdfPath);
File parent = file.getParentFile();
// 如果pdf保存路径不存在,则创建路径
if (!parent.exists()) {
parent.mkdirs();
}
StringBuilder sb = new StringBuilder();
sb.append(toPdfTool).append(" ").append(" \"").append(htmlPath).append("\" ").append(" ").append(pdfPath);
boolean result = true;
try {
Process proc = Runtime.getRuntime().exec(sb.toString());
try {
proc.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e) {
result = false;
e.printStackTrace();
}
return result;
}