码迷,mamicode.com
首页 > 其他好文 > 详细

Freemarker+IText生成pdf文件

时间:2016-10-26 11:25:57      阅读:523      评论:0      收藏:0      [点我收藏+]

标签:java   springmvc   mybatis   spring   shiro   

最近项目中遇到要用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>  


Freemarker+IText生成pdf文件

标签:java   springmvc   mybatis   spring   shiro   

原文地址:http://12218186.blog.51cto.com/12208186/1865716

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!