Java實現Html轉PDF

項目上的客戶提出一個需求,把政務流程中的表單數據導出成pdf或者圖片格式,用來作電子檔案材料。表單基於公司的電子政務構建平臺實現,在數據庫保存的都是html格式,因此打算直接把表單html轉成pdf或者圖片。由於表單是已經寫好了html頁面,那我要做的就是能完美解析html+css的pdf生成工具。在百度上搜索html轉pdf的結果,大部分都是用itext,itext的確是java開源組件的第一選擇。不過itext也有侷限,就是要自己寫模版,系統中的表單數量有好幾百個,爲每個表單做一個導出模版不現實。 

最後,wkhtmltopdf進入了我的選擇範圍。wkhtmltopdf是一個使用webkit網頁渲染引擎開發的用來將 html轉成 pdf的工具,可以跟多種腳本語言進行集成來轉換文檔。

官網地址 http://wkhtmltopdf.org/

github地址 https://github.com/wkhtmltopdf/wkhtmltopdf

wkhtmltopdf把html轉成pdf很簡單,只要在windows命令行中輸入

c:\wkhtmltopdf.exe http://www.csdn.net c:\csdn.pdf

就可以把csdn網頁轉成pdf,並保存到C盤根目錄。

在java中調用wkhtmltopdf的命令Runtime.getRuntime().exec("c:\wkhtmltopdf.exe http://www.csdn.net c:\csdn.pdf")就可以實現轉換。

下面把命令封裝成java工具類,方便調用。

[java] view plain copy
  1. import java.io.File;  
  2.   
  3. public class HtmlToPdf {  
  4.     //wkhtmltopdf在系統中的路徑  
  5.     private static final String toPdfTool = "c:\\wkhtmltopdf.exe";  
  6.       
  7.     /** 
  8.      * html轉pdf 
  9.      * @param srcPath html路徑,可以是硬盤上的路徑,也可以是網絡路徑 
  10.      * @param destPath pdf保存路徑 
  11.      * @return 轉換成功返回true 
  12.      */  
  13.     public static boolean convert(String srcPath, String destPath){  
  14.         File file = new File(destPath);  
  15.         File parent = file.getParentFile();  
  16.         //如果pdf保存路徑不存在,則創建路徑  
  17.         if(!parent.exists()){  
  18.             parent.mkdirs();  
  19.         }  
  20.           
  21.         StringBuilder cmd = new StringBuilder();  
  22.         cmd.append(toPdfTool);  
  23.         cmd.append(" ");  
  24.         cmd.append(srcPath);  
  25.         cmd.append(" ");  
  26.         cmd.append(destPath);  
  27.           
  28.         boolean result = true;  
  29.         try{  
  30.             Process proc = Runtime.getRuntime().exec(cmd.toString());  
  31.             HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());  
  32.             HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());  
  33.             error.start();  
  34.             output.start();  
  35.             proc.waitFor();  
  36.         }catch(Exception e){  
  37.             result = false;  
  38.             e.printStackTrace();  
  39.         }  
  40.           
  41.         return result;  
  42.     }  
  43. }  

接收Process的輸入和錯誤信息時,需要創建另外的線程,否則當前線程會一直等待(在Tomcat中有這種現象)。

[java] view plain copy
  1. import java.io.BufferedReader;  
  2. import java.io.IOException;  
  3. import java.io.InputStream;  
  4. import java.io.InputStreamReader;  
  5.   
  6. /** 
  7.  * 當java調用wkhtmltopdf時,用於獲取wkhtmltopdf返回的內容 
  8.  */  
  9. public class HtmlToPdfInterceptor extends Thread {  
  10.     private InputStream is;  
  11.       
  12.     public HtmlToPdfInterceptor(InputStream is){  
  13.         this.is = is;  
  14.     }  
  15.       
  16.     public void run(){  
  17.         try{  
  18.             InputStreamReader isr = new InputStreamReader(is, "utf-8");  
  19.             BufferedReader br = new BufferedReader(isr);  
  20.             String line = null;  
  21.             while ((line = br.readLine()) != null) {  
  22.                 System.outlprintln(line.toString()); //輸出內容  
  23.             }  
  24.         }catch (IOException e){  
  25.             e.printStackTrace();  
  26.         }  
  27.     }  
  28. }  

在Servlet中調用

[java] view plain copy
  1. /** 
  2.  * Html轉PDF 
  3.  */  
  4. @WebServlet("/htmltopdf/servlet")  
  5. public class HtmlToPdfServlet extends HttpServlet {  
  6.     private static final long serialVersionUID = 1L;  
  7.       
  8.     /** 
  9.      * Servlet接收參數path,獲取html的url 
  10.      */  
  11.     protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  12.         String path = request.getParameter("path");  
  13.         if(path == null || path.equals("")){  
  14.             return;  
  15.         }  
  16.           
  17.         //獲取pdf的臨時保存路徑  
  18.         //tmp爲網站下的目錄  
  19.         //把生成的pdf放到網站下以便下載  
  20.         String pdfPath = request.getSession().getServletContext().getRealPath("/tmp");  
  21.         String pdfName = UUID.randomUUID().toString() + ".pdf";  
  22.           
  23.         if(HtmlToPdf.convert(path, pdfPath + "/" + pdfName)){  
  24.             response.sendRedirect(request.getContextPath() + "/tmp/" + pdfName);  
  25.         }  
  26.     }  
  27. }  

在瀏覽器中輸入http://<網站路徑>/htmltopdf/servlet?path=http://blog.csdn.net

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