packagecom.jit.platform.basics.util.pdf;importjava.io.File;importjava.io.IOException;public classHtmlToImageOrPdf {
/*** html转pdf
*@paramsrcPath html路径,可以是硬盘上的路径,也可以是网络路径
*@paramdestPath pdf保存路径
*@return转换成功返回true
*@throwsInterruptedException
*@throwsIOException*/
public static void convert(String srcPath, String destPath,String width_height) throwsInterruptedException, IOException{
String toPdfTool=getCommand();
File file= newFile(destPath);
File parent=file.getParentFile();//如果pdf保存路径不存在,则创建路径
if(!parent.exists()){
parent.mkdirs();
}
//将软件路径、html路径、pdf生成路径、和一些形成pdf的参数加到字符串容器中。
StringBuilder cmd= newStringBuilder();
cmd.append(toPdfTool);
cmd.append(" ");
//cmd.append("--margin-top 0mm --margin-bottom 0mm --margin-right 0mm --margin-left 0mm ");
//cmd.append("--page-width "+width_px+" ");
//cmd.append("--page-height "+height_px+" ");
cmd.append(srcPath);
cmd.append(" ");
cmd.append(destPath);long begin =System.currentTimeMillis();
//利用cmd执行刚才添加的参数。
Process proc=Runtime.getRuntime().exec(cmd.toString());long end =System.currentTimeMillis();
System.out.println("形成html执行耗时:" + (end - begin) + " 豪秒");
HtmlToPdfInterceptor error= newHtmlToPdfInterceptor(proc.getErrorStream());
HtmlToPdfInterceptor output= newHtmlToPdfInterceptor(proc.getInputStream());
error.start();
output.start();
proc.waitFor();
}
//为满足window和linux系统,所以我们在这里进行判断public staticString getCommand(){
String system= System.getProperty("os.name");if(system.toLowerCase().indexOf("windows")>=0) //xp系统
return "D:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltoimage.exe"; //这里返回你wkhtmltoimage或wkhtmltopdf的exe文件的路径else if(system.toLowerCase().indexOf("linux")>=0) //linux 系统
return "wkhtmltopdf-amd64 ";return "";
}
}