`
coconut_zhang
  • 浏览: 531566 次
  • 性别: Icon_minigender_1
  • 来自: 天津
社区版块
存档分类
最新评论

flying sauser, thymeleaf实现PDF文件下载

阅读更多

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>

 

 

 

分享到:
评论
2 楼 coconut_zhang 2018-02-26  
这个demo 非常完整了,是指下面说的那个html 模版,模版引擎的作用是将模版文件和数据进行合成我们想要的报表。
1 楼 a93456 2017-09-09  
你好,你有完整的demo吗?
 String template这个指的什么

相关推荐

Global site tag (gtag.js) - Google Analytics