Using JasperReports from Java
So now you have a working JasperReports report. How do you use it from within your Java application?
The JasperDesign object, in the net.sf.jasperreports.engine package, is the Java representation of the XML report you designed using iReport. You load the XML report and compile it into a JasperReport object, which does the actual report generation:
In a real application, you shouldn't do this every time you generate a report, as it is time consuming and easily cached.
Once you have a compiled report, you can feed it data and use it to generate reports.
When you generate the report, you can provide runtime parameters via a Map. This is useful for providing information that is unknown at design time, such as a user-customized report title. From within the JasperReport report, you declare the parameter in the "View/Report Parameters" window and then use the parameter variable just like the other fields and variables you saw previously:
// Run-time report parameters
Map parameters = new HashMap();
parameters.put("title", "A user-customized title");
Of course, you also need to provide a valid JDBC connection to the target database:
// Fetch your database connection
Connection conn = DBConnectionFactory.getConnection();
Finally, you use the JasperFillManager class to combine the compiled report model with the incoming data to generate a print-ready report:
Now use the JasperPrintManager to generate the report in whatever format you want. JasperReport supports a lot of formats: PDF, Excel, XML, HTML, CVS, etc. But for now, just write the report to a PDF file:
There are lots of other possibilities. Check out the JasperReports APIs for more details.
Other Reporting Tools
A number of other reporting tools are available, so how does JasperReports/iReport stack up to the others? Here are a couple of the main actors in the field:
- Business Objects/Crystal Reports is a powerful commercial BI/reporting solution with a slick graphical designer. A full-fledged Crystal Reports Server XI Edition license (20 users) costs around $7,500. The Crystal Reports IX Developer Edition, a lighter version more oriented towards Web application development, is available for around $595 per developer. Even in the latest version, Java integration seems to be limited however.
A Dynamic Duo
JasperReports is powerful and flexible reporting tool, which is easy to integrate into a Java environment. iReport takes a lot of the hard work out of designing reports with JasperReportswithout comprising its power. Together, they form an impressive pair. Try it out!