我希望能够将使用 JasperReports 生成的报告作为附件发送。目前在我的应用程序中,我能够使用 JasperReportsViewResolver 查看报告,下面是我的配置
@Bean
public JasperReportsViewResolver getJasperReportsViewResolver() {
JasperReportsViewResolver resolver = new JasperReportsViewResolver();
resolver.setPrefix("classpath:/static/jasper/");
resolver.setSuffix(".jrxml");
resolver.setReportDataKey("datasource");
resolver.setViewNames("rpt_*");
resolver.setViewClass(JasperReportsMultiFormatView.class);
resolver.setOrder(0);
return resolver;
}
我无法从这个viewresolver获取输入资源,所以下面是我想的想法,但我不确定这是最好的方法
JasperDesign jasperDesign = JRXmlLoader.load(getClass().getResourceAsStream("/jasper/rpt_media.jrxml"));
JasperReport report = JasperCompileManager.compileReport(jasperDesign);
JRDataSource reportData = new JREmptyDataSource();
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("reportTitle", "dfa dafdf d dfd");
OutputStream stream = new FileOutputStream(tempfile);
JasperReportsUtils.renderAsPdf(report, parameters, reportData, stream);
将报告保存到随机文件后,我会将其读取并作为附件发送。
还有其他建议吗?
答案 0 :(得分:3)
我发现以下是最好的方式
JRDataSource ds = new JRBeanCollectionDataSource(reportList);
Resource report = new ClassPathResource("static/jasper/rpt_report.jasper");
JasperPrint jasperPrint = JasperFillManager.fillReport(report.getInputStream(), Collections.EMPTY_MAP,ds);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
JasperExportManager.exportReportToPdfStream(jasperPrint, baos);
DataSource aAttachment = new ByteArrayDataSource(baos.toByteArray(), "application/pdf");
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setTo("xxxxxx");
helper.setFrom("xxxxx");
helper.setSubject("Testing Email");
String text = "Testing Email";
helper.setText(text, false);
helper.addAttachment("report.pdf",aAttachment);
mailSender.send(message);