I would like to have a controller method returning a PDF from a JasperReports jrxml file, without using any xml configuration.
I would like to use a JasperReportsPdfView
. Is this possible at all? I know it can be done with only Java code like in this blog:
http://krams915.blogspot.com/2010/12/spring-3-mvc-jasper-integration_22.html
But I believe it must be possible with less code :-)
Here some example-code which does not work unfortunately.
@RequestMapping(value = "/test/pdfreport", method = RequestMethod.GET, produces = "application/pdf")
public JasperReportsPdfView getPdf() {
// does not work like this, unfortunately
final Person p = userService.getUserById("the id");
final JasperReportsPdfView view = new JasperReportsPdfView();
view.setReportDataKey("person");
view.addStaticAttribute("person", p); // ??
view.setUrl("report.jrxml");
return view;
}
Thanks for any pointer.
Edit: This is my working solution:
@Autowired
private ApplicationContext appContext;
@RequestMapping(value = "/test/pdfreport", method = RequestMethod.GET, produces = "application/pdf")
public ModelAndView getPdf() {
final List<Map<String, Object>> users = userService.getUsers();
final JasperReportsPdfView view = new JasperReportsPdfView();
view.setReportDataKey("users");
view.setUrl("classpath:report.jrxml");
view.setApplicationContext(appContext);
final Map<String, Object> params = new HashMap<>();
params.put("users", users);
return new ModelAndView(view, params);
}
It's important to include the spring-context-support
package to your project.