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

相關文章
相關標籤/搜索