thymeleaf 的资料比较少,资料大部分都是和spring mvc整合的,从后端返回数据,通过thymeleaf 标签在前台显示。项目中有一个需求,就是点击下载按钮,实现pdf下载。通过查找资料,pdf下载大概有三种方式:itext,flying sauser,jasperreport。itext不支持css样式,jasperreport需要设计模板,要学会模板设计工具ireport的使用。flying sauser 可以根据html文件生成pdf,并且支持css样式,这无疑是最佳的选择。
在web中实现下载功能,我们的思路大概是这样的:
1) 编写模板(thymeleaf ,Freemarker,Velocity),打造HTML,勾画PDF的样式(请任意使用CSS)
2) 在你的业务逻辑层引入模板引擎,并将业务逻辑层中可以获取的数据和模板,使用引擎生成最终的内容
3) 将内容生成PDF
从网上查找资料,Freemarker的比较多,经过尝试,终于通过thymeleaf 引擎把模板和数据生成了最终需要的内容,并实现下载。代码如下:
1. thymeleaf 模板(test.html)
2.生成下载内容
3.生成pdf(flying sauser)
4,下载函数
pom.xml
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf</artifactId>
<version>9.0.9</version>
</dependency>
为大家提供一些资料
api:
http://www.thymeleaf.org/apidocs/thymeleaf/2.1.4.RELEASE/index.html
标记的使用:
http://www.blogjava.net/bjwulin/archive/2013/02/07/395234.html
http://www.cnblogs.com/suncj/p/4028768.html
http://schy-hqh.iteye.com/blog/1961397
http://my.oschina.net/smile622/blog/339884
http://www.cnblogs.com/suncj/p/4028768.html
下载函数
public static void downloadFile(HttpServletRequest request, HttpServletResponse response, String fileName, String filePath) throws UnsupportedEncodingException, Exception, IOException { // 输出文件 response.setCharacterEncoding("utf-8"); response.setContentType("multipart/form-data"); // 中文文件名支持 String encodedfileName = null; String agent = request.getHeader("USER-AGENT"); if (null != agent && -1 != agent.indexOf("MSIE")) {// IE encodedfileName = java.net.URLEncoder.encode(fileName, "UTF-8"); } else if (null != agent && -1 != agent.indexOf("Mozilla")) { encodedfileName = new String(fileName.getBytes("GB2312"), "iso-8859-1"); } else { encodedfileName = java.net.URLEncoder.encode(fileName, "UTF-8"); } response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\""); InputStream inputStream = null; OutputStream os = null; try { inputStream = new FileInputStream(new File(filePath)); os = response.getOutputStream(); byte[] b = new byte[2048]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); } } catch (Exception e) { throw e; } finally { if (os != null) { os.close(); } if (inputStream != null) { inputStream.close(); } } }
生成pdf(flying sauser)
String path = request.getSession().getServletContext().getRealPath(""); String filePath = path + env.getProperty("outputPath") + File.separator + UUIDUtil.getShortUuid() + ".pdf"; OutputStream out = new FileOutputStream(filePath); Map<String, String> map = new HashMap<String, String>(); map.put("name", "张三"); map.put("score", "100000"); String fileTemplatePath = path + env.getProperty("templatePath") + File.separator; String htmlStr = HtmlGenerator.generate(fileTemplatePath, "test", map); DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(new ByteArrayInputStream(htmlStr.getBytes("UTF-8"))); ITextRenderer renderer = new ITextRenderer(); ITextFontResolver fontResolver = renderer.getFontResolver(); fontResolver.addFont("C:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); fontResolver.addFont("C:/Windows/Fonts/simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); renderer.setDocument(doc, null); renderer.layout(); renderer.createPDF(out); out.close(); // 下载文件 String fileName = "test.pdf"; ExcelUtil.downloadFile(request, response, fileName, filePath);
生成下载内容(使用thymeleaf 引擎)
public class HtmlGenerator { public static String generate(String filePath, String template, Map<String, String> variables) throws Exception{ //创建模板解析器 FileTemplateResolver templateResolver = new FileTemplateResolver(); templateResolver.setPrefix(filePath); templateResolver.setSuffix(".html"); templateResolver.setCharacterEncoding("UTF-8"); templateResolver.setTemplateMode("XHTML"); templateResolver.setCacheTTLMs(Long.valueOf(3600000L)); templateResolver.setCacheable(true); //创建模板引擎并初始化解析器 TemplateEngine engine = new TemplateEngine(); engine.setTemplateResolver(templateResolver); engine.initialize(); //输出流 StringWriter stringWriter = new StringWriter(); BufferedWriter writer = new BufferedWriter(stringWriter); //获取上下文 Context ctx = new Context(); ctx.setVariables(variables); engine.process(template, ctx, writer); stringWriter.flush(); stringWriter.close(); writer.flush(); writer.close(); //输出html String htmlStr = stringWriter.toString(); return htmlStr; } public static void main(String args[]) throws Exception { String Str = generate("d:\\","test",new HashMap<String, String>()); System.out.println(Str); } }
thymeleaf 模板(test.html)
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <title>Thymeleaf!!!!!</title> <meta http-equiv="Content-Type" content="text/html;" charset="UTF-8"/> <style type="text/css"> body { font-size: 10pt; color: #333333; font-family:SimHei} thead { font-weight: bold; background-color: #C8FBAF; } td { font-size: 10pt; text-align: center; } </style> </head> <body> <h1>Thymeleaf template Test</h1> <h1>充值合同测试</h1> <table> <thead> <tr> <th>姓名</th> <th>成绩</th> </tr> </thead> <tbody> <tr> <td th:text="${name}"></td> <td th:text="${score}"></td> </tr> </tbody> </table> </body> </html>
相关推荐
flying sauser,基于iText自身的问题,让我们开始寻求可以真正意义上模版技术,那么flying sauser就是为了这个问题出现的产品,能解析HTML和CSS,而且能输出成image,PDF等格式。具体使用,请访问:...
NULL 博文链接:https://cuiyaoonan2000.iteye.com/blog/2173135
官方指导手册,教你如何使用
NULL 博文链接:https://yongboy.iteye.com/blog/510976
Flying Sauser实现html2pdf,纠错能力差,支持多种中文字体(部分样式不能识别),而且对html的格式也是十分的严格,如果使用一种模版的话使用Flying Sauser技术倒是不错的选择,但是对于不规则的html导出pdf就并...
Flying Sauser、html2pdf、iText-2.0.8.jar、iTextAsian.jar、core-renderer.jar
此资源包包含了用struts下载带有页眉页脚水印的pdf文件,并且页眉页脚处放的是图片加文字,还带有页码,其中用到的技术freemarker+itext+flying sauser整合开发,由于是刚从工程中抠出来的,不能运行起来,但功能是完好...
依赖jar包:fonts.jar pd4ml.jar ss_css2.jar PD4ML实现html2pdf,速度快,纠错能力强,支持多种中文字体。相比较于IText和Flying Sauser方便许多
iText-2.0.8.jar,Freemarker+Flying sauser +Itext 整合生成PDF需要的JAR包,配合core-renderer.jar一起使用
由于工作所需,最近花时间研究了html转换为pdf的功能。...本次测试类有:IText,Flying Sauser,PD4ML。js 前端解析模式:js前端解析html文件为pdf文件,本次测试案例有:html2canvas。 本次针对网上介
书名:Systems thinking :coping with 21st century problems /John Boardman, Brian Sauser. ISBN:9781420054910(alk.paper) 作者:Boardman John 1946-. 出版社:Boca Raton, FL :CRC Press,c2008.
EXEC sp_grantdbaccess 'sa','sauser' 给数据库用户授权 授权的语法 grant select,insert,update on scorelist to sauser 收回授权的语法 REVOKE SELECT ON scorelist to sauser 固定角色 角色名称 角色描述 ...