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
| public class PdfReportView extends AbstractView {
private static final String CONTENT_TYPE = "application/pdf";
private String templatePath; private String exportFileName; private Connection connection;
public PdfReportView(String templatePath, String exportFileName,Connection connection) { this.templatePath = templatePath; if (exportFileName != null) { try { exportFileName = URLEncoder.encode(exportFileName, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } this.exportFileName = exportFileName; this.connection = connection; setContentType(CONTENT_TYPE); }
protected 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 request, HttpServletResponse response) throws Exception {
response.setCharacterEncoding("utf-8"); response.setContentType(getContentType()); response.setHeader("content-disposition", "attachment;filename=" + exportFileName + ".pdf");
try (InputStream inputStream = Thread.currentThread().getContextClassLoader() .getResourceAsStream(templatePath)) { try (OutputStream ouputStream = response.getOutputStream()) {
JasperPrint jasperPrint = JasperFillManager .fillReport(inputStream, getParamsMap(map), connection);
JasperExportManager.exportReportToPdfStream(jasperPrint, ouputStream); } catch (IOException e) { e.printStackTrace(); }finally { connection.close(); } } catch (IOException e) { e.printStackTrace(); }
} }
|