我建议实施您自己的 PdfView。
我将演示它:
public class JasperPdfView extends AbstractView {
public JasperPdfView(){
setContentType("application/pdf");
}
@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
final JasperPrint print = (JasperPrint)model.get("jasper_print");
JasperExportManager.exportReportToPdfStream(print, response.getOutputStream());
}
}
我有一个服务可以创建我将传递给视图的 JasperReport 对象。
@Override
public JasperPrint generate(ReportContext ctx) throws SQLException {
Resource res = resourceLoader.getResource(ctx.getFile());
JasperReport report = JasperCompileManager.compileReport(res.getInputStream());
HashMap<String, Object> map = Maps.newHashMap();
map.putAll(ctx.getParams());
map.put("from", ctx.getFrom().toDate());
map.put("to", ctx.getTo().toDate());
JasperPrint print = JasperFillManager.fillReport(report, map, dataSource.getConnection());
return print;
}
我的控制器生成调用服务并将 JasperReport 放在模型上。
@RequestMapping(value = "/{reportName}")
public void printReport(@PathVariable final String reportName, final ParameterForm form, final ModelMap model)
throws SQLException {
final ReportContext ctx = reports.get(reportName).build();
ctx.setFrom(form.getFrom());
ctx.setTo(form.getTo());
ctx.getParams().put("customerId",form.getCustomerId());
model.put("jasper_print", reportService.generate(ctx));
}
JapserPdfView 是通过 ContentNegotiatingViewResolver 确定的。