html转pdf工具:使用Java调用wkhtmltopdf将html转为pdf

1、wkhtmltopdf安装
linux环境下安装(centos6.5)
1.安装依赖
$ yum install -y xorg-x11-fonts-75dpi
$ yum install -y xorg-x11-fonts-Type1
$ yum install xz
2. 获取安装包(可根据须要获取不一样版本)
$ wget https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
或者直接到 github获取下载安装包上传
3.解压
$ unxz wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
$ tar -xvf wkhtmltox-0.12.4_linux-generic-amd64.tar
$ mv wkhtmltox /usr/local/wkhtmltox
添加执行命令到系统路径
export PATH=/usr/bin/wkhtmltox/bin:$PATH
移除安装包
$ rm wkhtmltox-0.12.4_linux-generic-amd64.tar
测试生成pdf
$wkhtmltopdf www.baidu.com baidu.pdf
2、Java调用wkhtmltopdf将html生成pdfhtml

public class HtmlToPdfUtils {
	//windows
	private static String toolWinPath = "D:\\\\software\\\\wkhtmltox-0.12.5-1.mxe-cross-win64\\\\bin\\\\wkhtmltopdf.exe";
	//Linux
	private static String toolLinuxPath = "/usr/bin/wkhtmltox/bin/wkhtmltopdf";
	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();
		if(System.getProperty("os.name").indexOf("Windows") == -1){
			//linux系统下wkhtmltopdf安装路径
			cmd.append(toolLinuxPath);
		} else
			cmd.append(toolWinPath);
		cmd.append(" \"").append(srcPath).append("\"").append(" ").append(destPath);
		boolean result = true;
		try {
			Process proc = Runtime.getRuntime().exec(cmd.toString());
			proc.waitFor();
		} catch (IOException | InterruptedException e) {
			result = false;
			e.printStackTrace();
		}
		return result;
	}
	public static void main(String[] args) {
		HtmlToPdfUtils.convert("http://www.baidu.com", "C:\\baidu.pdf");
	}
}


3、使用过程当中可能会遇到的问题
1.pdf生成后中文不显示
解决方法:多是系统缺乏字体文件,wkhtmltopdf要求生成pdf中若是包含中文,那么系统中至少要包含宋体,能够下载字体文件(simsun.ttc)上传到/usr/share/fonts目录下java

2.生成pdf中若是超链包含中文,在linux环境中生成以后可能会乱码linux

解决方法:使用URLEncoder将超链编码后再生成git

相关文章
相关标签/搜索