1. 安装下载 傻瓜式安装2. 环境变量path 系统变量 添加 (wkhtmltopdf安装位置\bin)3. 测试命令行:wkhtmltopdf http://www.baidu.com/ C:\\wkhtmltopdf\\test.pdf
wkhtmltopdf:调用==+==html地址==+==文件位置及命名
效果:
生成百度首页pdf 类似截图效果 成功4. 封装程序package skillTree;
import java.io.*;
class HtmlToPdfInterceptor extends Thread{
private InputStream is;
public HtmlToPdfInterceptor(InputStream is){
this.is = is;
}
public void run(){
try{
InputStreamReader isr = new InputStreamReader(is,"utf-8");
BufferedReader br =new BufferedReader(isr);
String line;
while((line = br.readLine()) != null){
System.out.println(line);
}
}catch(IOException e){
e.printStackTrace();
}
}
}
public class HtmlToPdf {
private static final String toPdfTool = "C:\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
public static boolean convert(String srcPath, String destPath){
File file = new File(destPath);
File parent = file.getParentFile();
if(!parent.exists())
parent.mkdirs();
StringBuilder cmd = new StringBuilder();
cmd.append(toPdfTool);
cmd.append(" ");
cmd.append(srcPath);
cmd.append(" ");
cmd.append(destPath);
boolean result = true;
try{
Process proc = Runtime.getRuntime().exec(cmd.toString());
HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getErrorStream());
error.start();
output.start();
proc.waitFor();
}catch(Exception e){
result = false;
e.printStackTrace();
}
return result;
}
public static void main(String[] args){
convert("http://www.stats.gov.cn/","C:\\wkhtmltopdf\\test.pdf");
}
}
效果:
待
|