How to use JasperReportsPdfView without xml config

2019-06-27 14:11发布

问题:

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.

回答1:

This works for me:

@Autowired private ApplicationContext appContext;
@Autowired private DataSource dataSource;

@RequestMapping(value = "/pdf", method = RequestMethod.GET)
public ModelAndView getPdf() {
    JasperReportsPdfView view = new JasperReportsPdfView();
    view.setJdbcDataSource(dataSource);
    view.setUrl("classpath:report.jrxml");
    Map<String, Object> params = new HashMap<>();
    params.put("param1", "param1 value");
    view.setApplicationContext(appContext);
    return new ModelAndView(view, params);
}