JasperReportsPdfView.java
2.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.huaheng.framework.jasper;
import net.sf.jasperreports.engine.*;
import org.springframework.web.servlet.view.AbstractView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
/**
* 通用导出PDF视图类
* @author ricard
* @time 19/11/15
*
*/
public class JasperReportsPdfView extends AbstractView {
//继承AbstractView
//内容类型,即格式
private static final String CONTENT_TYPE = "application/pdf";
//模板路径
private String templatePath;
//导出文件名
private String exportFileName;
//重置构造方法
public JasperReportsPdfView(String templatePath,String exportFileName){
this.templatePath = templatePath;
if (exportFileName != null) {
try {
exportFileName = URLEncoder.encode(exportFileName, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
this.exportFileName = exportFileName;
setContentType(CONTENT_TYPE);
}
public Map<String,Object> getParamsMap(Map<String,Object> map) throws Exception{
Map<String,Object> params =new HashMap<>();
for(String key : map.keySet()){
Object val = map.get(key);
if(val instanceof JRDataSource){
continue;
}else {
params.put(key,val);
}
}
return params;
}
protected JRDataSource getDataSource(Map<String,Object> map) throws Exception{
for(String key : map.keySet()){
Object val = map.get(key);
if(val instanceof JRDataSource){
return (JRDataSource) map.get(key);
}
}
return new JREmptyDataSource();
}
@Override
protected void renderMergedOutputModel(Map<String, Object> map, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//设置编码和格式
httpServletResponse.setCharacterEncoding("utf-8");
httpServletResponse.setContentType(getContentType());
httpServletResponse.setHeader("content-disposition","attachment;filename=" + exportFileName);
try(
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(templatePath)
){
try(OutputStream outputStream = httpServletResponse.getOutputStream()){
JasperPrint jasperPrint = JasperFillManager.fillReport(inputStream,getParamsMap(map),getDataSource(map));
JasperExportManager.exportReportToPdfStream(jasperPrint,outputStream);
}catch (IOException e){
e.printStackTrace();
}
}catch (IOException e){
e.printStackTrace();
}
}
}