Freemarker+IText生成pdf文件

最近項目中遇到要用html生成pdf文件的需求,一開始研究了下前端插件jspdf,使用h5 canvas繪圖生成圖片,再把圖片生成pdf文件,遇到了各種各樣的問題,生成的pdf文件達到20多M,height超過5000瀏覽器就崩潰,有興趣的童鞋可以嘗試一下,該方案LZ最終放棄了。

       接着開始嘗試服務端生成,使用freemaker模板生成靜態html文件,通過iext生成pdf,網上很多關於renderer.setDocument(dom,null)的用法,LZ嘗試後發現效率奇低,最後放棄了,直接使用renderer.setDocumentFromString方法,要注意以下幾點:

       1、生成的html聲明文件,xhtml部分要幹掉,否則解析報錯。

       2、注意設置相對目錄,一定要物理絕對目錄,否者css和img文件就找不到了。

       3、生成pdf時中文的問題,就是要加載字體文件simsun.ttc,這個網上解決方案不少,不做贅述,注意html加上樣式。

Html代碼  收藏代碼

  1. <style>  

  2. body{  

  3.     font-family: SimSun;  

  4. }  

  5. </style>  

 

Java代碼  收藏代碼

  1. public void exportPDF() throws Exception  

  2. {  

  3.     OutputStream os = null;  

  4.     String htmlStr;  

  5.     Map<String, Object> params = new HashMap<String, Object>();  

  6.     Map data = new HashMap();  

  7.     try {  

  8.         /** 

  9.                 xxx數據生成邏輯 

  10.                 **/  

  11.         data.put("projects",xxx);  

  12.           

  13.         //通過freemaker模板生成html  

  14.         htmlStr = HtmlGenerator.generate("pdf.ftl", data);  

  15.         String appPath = getReq().getSession().getServletContext().getRealPath(File.separator);  

  16.         ITextRenderer renderer = new ITextRenderer();  

  17.         renderer.setDocumentFromString(htmlStr,"file:" + File.separator + appPath);  

  18.   

  19.         // 解決中文支持問題  

  20.         ITextFontResolver fontResolver = renderer.getFontResolver();  

  21.         fontResolver.addFont(appPath + "template" + File.separator +"simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);  

  22.           

  23.         //生成pdf文件  

  24.         getRes().setHeader("Content-disposition""attachment;filename=" + URLEncoder.encode("測試""UTF-8") + new Date().getTime() + ".pdf");       

  25.         getRes().setContentType("application/pdf");  

  26.         os = getRes().getOutputStream();  

  27.         renderer.layout();  

  28.         renderer.createPDF(os, true);  

  29.           

  30.         os.flush();  

  31.     } catch (Exception e) {  

  32.         e.printStackTrace();  

  33.     }finally {  

  34.         if (null != os) {  

  35.             try {  

  36.                 os.close();  

  37.             } catch (IOException e) {  

  38.                 throw new Exception(e);  

  39.             }  

  40.         }  

  41.     }  

  42.       

  43. }  

    HtmlGenerator類,編碼設置UTF-8,設置正確,不然有中文亂碼問題。下載

Java代碼  收藏代碼

  1. package com.haziwang.rkhy.util;     

  2.     

  3. import java.io.BufferedWriter;  

  4. import java.io.StringWriter;  

  5. import java.util.Map;  

  6. import freemarker.template.Configuration;  

  7. import freemarker.template.Template;     

  8.     

  9. public class HtmlGenerator {     

  10.     /** 

  11.      * @param template 

  12.      * @param variables 

  13.      * @return 

  14.      * @throws Exception 

  15.      */  

  16.     public static String generate(String template, Map params) throws Exception{     

  17.         Configuration config = FreemarkerConfiguration.getConfiguation();    

  18.         config.setDefaultEncoding("UTF-8");  

  19.         Template tp = config.getTemplate(template);     

  20.         StringWriter stringWriter = new StringWriter();   

  21.         BufferedWriter writer = new BufferedWriter(stringWriter);    

  22.         tp.setEncoding("UTF-8");       

  23.         tp.process(params, writer);       

  24.         String htmlStr = stringWriter.toString();     

  25.         writer.flush();       

  26.         writer.close();     

  27.         return htmlStr;     

  28.     }     

  29.     

  30. }    

    FreemarkerConfiguration類,設置ftl文件目錄,相對於classes目錄設置下載

Java代碼  收藏代碼

  1. package com.haziwang.rkhy.util;  

  2.   

  3. import freemarker.template.Configuration;  

  4.   

  5. public class FreemarkerConfiguration {     

  6.          

  7.     private static Configuration config = null;     

  8.          

  9.     /**   

  10.      * Static initialization.   

  11.      *    

  12.      * Initialize the configuration of Freemarker.   

  13.      */    

  14.     static{     

  15.         config = new Configuration();     

  16.         config.setClassForTemplateLoading(FreemarkerConfiguration.class"/../../template/");     

  17.         config.setTemplateUpdateDelay(0);  

  18.     }     

  19.          

  20.     public static Configuration getConfiguation(){     

  21.         return config;     

  22.     }     

  23.     

  24. }    

   代碼目錄結構下載

    maven引入jar包

Xml代碼  收藏代碼

  1. <dependency>  

  2.     <artifactId>  

  3.         flying-saucer-pdf-itext5  

  4.     </artifactId>  

  5.     <groupId>  

  6.         org.xhtmlrenderer  

  7.     </groupId>  

  8.     <version>  

  9.         9.0.6  

  10.     </version>  

  11. </dependency>  

  12. <dependency>  

  13.     <artifactId>  

  14.         freemarker  

  15.     </artifactId>  

  16.     <groupId>  

  17.         freemarker  

  18.     </groupId>  

  19.     <version>  

  20.         2.3.8  

  21.     </version>  

  22. </dependency>  


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