asperReports, a powerful, flexible open-source reporting engine, is easy to integrate into Java enterprise applications, but it lacks an integrated visual report editor. So, if you want to use JasperReports directly, you need to manipulate its XML report structurea relatively technical activity with a high learning curve, to say the least.
In fact, writing a full JasperReport from scratch using only the XML format is a long, painful, and unrewarding task.
Luckily, some available alternatives are much easier. The first and foremost of which is to use a visual editor to design, compile, and test your reports.
One of the most useful visual editors you can use is iReport. This article demonstrates how to use iReport to leverage the full power of JasperReports without getting entangled in complexities of the JasperReports native XML format.
The iReport download comes with its own JasperReports package (the latest version to date, 0.5.1, supports the recently released JasperReports 1.0.1).
![]() | |
| Figure 1. The Tutorial's Employee Database Schema |
Once you have iReport running, you can start designing your reports!
![]() | |
| Figure 2. Adding a New Database Connection |
Now that you have a datasource, it's time to do something with it.
![]() | |
| Figure 3. A New JasperReports Report |
Create a new JasperReports document using the "File/New Document" menu entry. You can ignore all the various options for now. Just give the report a name. You will get an empty report, as shown in Figure 3.
A JasperReport report is divided into the following display sections, illustrated in the iReport screen:
![]() | |
| Figure 4. The Report Query |
First, specify an appropriate SQL query for your report, using the Datasource/Report Query menu (see Figure 4). The query will request a list of all the employees in the database:
select * from employee e, service s
where e.serv_id = s.serv_id
order by s.serv_name, e.emp_surname, e.emp_firstname
![]() | |
| Figure 5. Report Fields |
You can visualize the field list using the "View/Report Fields" menu (see Figure 5).
![]() | |
| Figure 6. Laying Out Report Fields |
When you create a SQL query, this list automatically updates with the fields your query returns. In cases in which you use other types of datasources, you may have to define the fields by hand.
![]() | |
| Figure 7. Preview Report Results |
From the report fields window, you can drag and drop fields onto your report. Fields usually go into the Detail section, as Figure 6 illustrates. Place three fields into the Detail section, along with appropriate column titles in the Column Header section. The column titles are static text items, which you can insert by using either the "T" icon or the "Insert Element/Static Text" menu item. Play around with the formatting and layout options to become familiar with what iReport has to offer in this domain.
To test the whole thing, run the report using the "Build/Execute Report (using active conn.)" menu item. You should get something like the report in Figure 7.
![]() | |
| Figure 8. Add a Date Field |
Now, suppose you want to display today's date as well. Insert a new text field ("Edit/Insert Element/Text Field"). Double-click on the text field object and go to the "TextField" tab in the window that just appeared (see Figure 8).
Here you get a glimpse of the power of JasperReports. Because a compiled JasperReport is a Java class, you can use any Java expression to help build your report, as well as JasperReports fields, variables, and parameters. For instance, the "TextField" expression is a Java expression and will be interpreted as such.
![]() | |
| Figure 9. The Report with a Title Bar |
To display the current date, you just create a new Date() object, which will automatically be instantiated to the current date and time. Then you tell JasperReports the expression type (in the Textfield Expression class: java.util.Date) to use, when to evaluate the expression (Evaluation time), and which format to use (the "Pattern field").
As a final touch, add a transparent border around the title ("Edit/Insert Element/Rounded Rectangle") and an image ("Edit/Insert Element/Image"), and then customize the colors and fonts (see Figure 9 for an example).
Date())
![]() | |
| Figure 10. Adding a New Variable |
To display the report variables, open the "View/Report Variables" menu. You need to add a new variable to track employee salaries and calculate the total value. Let's call it total_salaries (see Figure 10). Set the variable class type to Double and the calculation type to Sum.
![]() | |
| Figure 11. Calculating the Total Salaries |
For now, you need to evaluate the 'emp_salary' field, so enter "$F{emp_salary}" as the variable expression.
Now drag this variable into the Column Footer section, and add an appropriate text title (see the generated report in Figure 11). Using the same approach, you can easily add other types of variables: averages, counts, lowest and highest values, and so on.
![]() | |
| Figure 12. Adding a New Group |
The most important field here is 'Group Expression'. Each time this expression changes, a new group generates. So, to group records by service, use the service name field ("$F{serv_name}"). As you would expect, for this to work property, you must correctly order the SQL query ordering ("order by serv_name,...").
![]() | |
| Figure 13. Adding a New Group |
When you add a new group, you get two new sections: "serviceHeader" and "serviceFooter". These sections are generated at the start and end of each service group, respectively. Reposition the static column headers into the "serviceHeader" section, and place the $F{serv_name} field just above these columns to act as a group heading.
Now create a new variable called service_salary_subtotal, as illustrated in Figure 13. It is similar to the previous variable, but with two important differences: Reset Type is 'Group', and Reset Group is 'service', meaning that the variable will be reset to zero at the start of each new service group.
![]() | |
| Figure 14. The Grouped Report Layout |
Drag this variable into the "serviceFooter" section to display the subtotal of all salaries for each group. The layout should look something like the one in Figure 14. The generated report should look something like Figure 15.
![]() | |
| Figure 15. The Grouped Report |
![]() | |
| Figure 16. Chart Design |
Click on the new chart, and go to the 'Chart' tab. Once there, click on the 'Edit Chart Properties' button and go to the 'Chart data' tab (see Figure 16).
![]() | |
| Figure 17. Chart Report |
Chart parameters are different for each type of chart. The 'Chart data' tab for a pie chart has three zones:
Now run the report. You should get a pie chart at the end of your report (see Figure 17).
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:
JasperDesign jasperDesign
= JasperManager.loadXmlDesign("MyReport.xml");
JasperReport jasperReport
= JasperManager.compileReport(jasperDesign);
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:
JasperPrint jasperPrint
= JasperFillManager.fillReport(jasperReport,
parameters,
conn);
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:
JasperExportManager.exportReportToPdfFile(jasperPrint,
"report.pdf");
There are lots of other possibilities. Check out the JasperReports APIs for more details.
| DevX is a division of Internet.com. © Copyright 2010 Internet.com. All Rights Reserved. Legal Notices |