wkhtmltopdf包使用

wkhtmltopdf


1. 安装

http://wkhtmltopdf.org/downloads.html
下载 傻瓜式安装

2. 环境变量

path 系统变量 添加 (wkhtmltopdf安装位置\bin)

3. 测试

命令行:

wkhtmltopdf http://www.baidu.com/ C:\\wkhtmltopdf\\test.pdf

wkhtmltopdf:调用==+==html地址==+==文件位置及命名

效果:

图片alt
生成百度首页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 {
	/* wkhtmltopdf 在系统中的路径*/
	private static final String toPdfTool = "C:\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";

	/*	html转pdf
	 * 	@param srcPath 	html路径或url
	 * 	@param destPath pdf保存路径
	 * 	@return 		成功返回true
	 */
	public static boolean convert(String srcPath, String destPath){
		File file = new File(destPath);
		File parent = file.getParentFile();
		//如果pdf路径不存在,创建
		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");
	}
}

效果:

图片alt

  • 网页图片等资源异步加载问题:

    延迟?
  • 简历生成:

    事先准备好一个需要生成pdf的html模板,数据全用占位符占位,等到需要生成pdf的时候,首先向文件里面写入数据(数据库交互),然后调用封装类生成pdf文件。