Java之集成wkhtmltopdf的基礎教程

之前用過一次wkhtmltopdf忘了,綜合網上查找的資料,這次寫下來記錄一下。

安裝步驟(Linux):

1. 根據自己的Linux版本從下面網址下載快很多,官網太慢了
wkhtmltopdf各版本地址(推薦):GitHub版本地址

wkhtmltopdf的centos7版本下載地址:wkhtmltopdf的centos7版本下載

官網(太慢不推薦)地址:官網
2. 部署教程
隨便找個路徑上傳安裝包,我的路徑是/usr/local/wkhtmltopdf,輸入如下命令
rpm -ivh wkhtmltox-0.12.5-1.centos7.x86_64.rpm
出現缺少依賴,根據提示缺少什麼就yum什麼。我這缺少的依賴包如下:
yum install xorg-x11-fonts-75dpi.noarch
yum install xorg-x11-fonts-Type1.noarch
yum install libXrender
yum install libXext
再次rpm -ivh wkhtmltox-0.12.5-1.centos7.x86_64.rpm安裝即可
3. 測試
測試命令
wkhtmltopdf http://www.baidu.com.com test.pdf
wkhtmltopdf hmlt地址 pdf轉換後存儲地址
當前目錄下,也就是你執行命令的當前目錄下會出現test.pdf文件,說明安裝成功
找到安裝目錄,我這安裝目錄是: /usr/local/bin/wkhtmltopdf
4. 檢查字體
需要存在simsun.ttc字體,避免pdf中文亂碼,如下目錄
/usr/share/fonts/simsun/simsun.ttc
windows版本就不多說自己下了,是個exe安裝程序,安裝好了就行,自己去系統變量path設置F:\wkhtmltopdf\1\wkhtmltopdf\bin全局變量。

Java集成:

核心代碼:

Runtime.getRuntime().exec();

HtmlToPdfInterceptor.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
 * wkhtmltopdf.exe執行信息攔截
 *
 */
public 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 = null;
	            while ((line = br.readLine()) != null) {
	                System.out.println(line.toString()); //輸出內容
	            }
	        }catch (IOException e){
	            e.printStackTrace();
	        }
	    }
}

HtmlToPdf.java

import java.io.File;
import com.rf.arb.Interceptor.HtmlToPdfInterceptor;

public class HtmlToPdf {
	//wkhtmltopdf在系統中的路徑
    private static final String toPdfTool = "F:\\wkhtmltopdf\\1\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
    
    /**
     * html轉pdf
     * @param srcPath html路徑,可以是硬盤上的路徑,也可以是網絡路徑
     * @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();
		if(System.getProperty("os.name").indexOf("Windows") == -1){
			//非windows 系統
			//toPdfTool = FileUtil.convertSystemFilePath("/home/ubuntu/wkhtmltox/bin/wkhtmltopdf");
		}
		cmd.append(toPdfTool);
		cmd.append(" ");
		/*
		cmd.append("  --header-line");//頁眉下面的線
		//cmd.append("  --header-center 這裏是頁眉這裏是頁眉這裏是頁眉這裏是頁眉 ");//頁眉中間內容
		cmd.append("  --margin-top 3cm ");//設置頁面上邊距 (default 10mm) 
		cmd.append(" --header-html  file:///"+WebUtil.getServletContext().getRealPath("")+FileUtil.convertSystemFilePath("\\style\\pdf\\head.html"));// (添加一個HTML頁眉,後面是網址)
		cmd.append(" --header-spacing 5 ");//    (設置頁眉和內容的距離,默認0)
		//cmd.append(" --footer-center (設置在中心位置的頁腳內容)");//設置在中心位置的頁腳內容
		cmd.append(" --footer-html  file:///"+WebUtil.getServletContext().getRealPath("")+FileUtil.convertSystemFilePath("\\style\\pdf\\foter.html"));// (添加一個HTML頁腳,後面是網址)
		cmd.append(" --footer-line");//* 顯示一條線在頁腳內容上)
		cmd.append(" --footer-spacing 5 ");// (設置頁腳和內容的距離)
		*/
		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.getInputStream());
            error.start();
            output.start();
            proc.waitFor();
        }catch(Exception e){
            result = false;
            e.printStackTrace();
        }
        
        return result;
    }
    public static void main(String[] args) {
        HtmlToPdf.convert("F:\\wkhtmltopdf\\test\\test.html", "F:\\wkhtmltopdf\\test\\test1.pdf");
    }
}

偷懶的同學直接複製上述代碼,類名一致即可測試,hmlt路徑和pdf存儲路徑跟代碼一致就行。重要說明,toPdfTool 需要你的window安裝的wkhtmltopdf絕對路徑。

至於代碼中的WebUtil.java和FileUtil.java,我查的資料沒有給明源代碼,所以我把部分cmd.append()的代碼註釋,這並不影響pdf的轉換,親測可用。

總結:

1.完全可以按照文中的教程一步一步來,文中所需的各種路徑完全可以一致,上手後根據自己需求更改。

2.部署過程中,可能缺少的依賴會更多,也可能會少,並不是一定跟文中所提的依賴缺少相同,切記根據提示來yum缺少依賴。

最後說一句,文中有錯誤,或者部署和集成過程中有不可解決的問題,可以評論下來,我會及時並不日回覆。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章