Open Source Java Reporting with JasperReports and iReport

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 structure?a 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.

Getting Started

The first thing to do is download and install iReport. It is a Java application, so you will need a JDK on your machine (JDK 1.4 or higher). This tutorial uses JDK 1.5.0:

  1. Download iReport from ireport.sourceforge.net.
  2. Decompress the iReport archive.
  3. Run the startup script (binstartup.bat or ./bin/startup.sh).

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!

The Example Database

This tutorial uses a very simple database (see Figure 1) for demonstration. To follow along step-by-step, either download the scripts for setting up this database with MySQL and set it up on your machine, or use a similar database and translate the techniques to your situation.

Figure 2. Adding a New Database Connection

Adding a New Database Connection

First, add a new connection to your database. Use the “Datasource -> Connections/Datasources” menu to set up a new database connection (see Figure 2). If you chose the JDBC driver in the list (the example chooses MySQL), enter the server address and the database name, and then click on the ‘Wizard’ button. iReport should provide you with a correct JDBC URL for your particular database.

Now that you have a datasource, it’s time to do something with it.

Creating a Simple Report

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:

  1. Title: As the name indicates, this section contains the report title. It is generated only once and appears only at the very start of the report.
  2. Page Header: This section appears at the top of each page?as you would expect. It is a good place for dates, page numbers, etc.
  3. Column Header: This section goes at the top of each column.
  4. Detail: This is where the information for each record entry is placed. JasperReports generates a detail section for each and every record it processes.
  5. Column Footer: This section goes at the bottom of each column.
  6. Page Footer: This section appears at the bottom of each page.
  7. Last Page Footer: This section goes at the bottom of the last page.
  8. Summary: This section appears right at the end of the report, just after the last record.
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 swhere e.serv_id = s.serv_idorder by s.serv_name, e.emp_surname, e.emp_firstname
Figure 5. Report Fields

Report Fields

Each JasperReports report has a list of fields, which are used to place data records coming from the database query in the report layout.

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.

Adding a Report Title and Date

So now you can generate a report with real data. Next, add a title in the title bar. This title will be displayed only at the very start of the report. Suppose you want the title for this report to be “Employees/service”, followed by the current date. To integrate the “Employees/Service” text, just place a static text zone in the title section (use “Edit/Insert Element/Static Text” or the “T” icon).

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).

Calculating Totals

Now suppose you want to display the total cost of all employee salaries. To calculate values like this in JasperReports, you need to use report variables. You use report variables to store and calculate any temporary values you need in the report, such as totals, sub-totals, averages, and so on. Here are some important things you should know about report variables:

  • The variable class type must match the field type for calculations to work properly. So here, set it to Double.
  • The calculation type tells JasperReports how to calculate the variable. Here, set it to ‘Sum’ to find the total of all the emp_salary field values.
  • The variable expression represents the value to be evaluated in the calculation. This expression can take many forms:
    • A Java expression (e.g., New Date())
    • $F for fields (e.g., “$F{emp_salary}”)
    • $V for variables (e.g., “$V{service_employee_count}”)
    • $P for report parameters
    • $R for localized resources
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.

Adding Groups

Now, suppose you want to group employees by service, and calculate a subtotal of salaries for each service. The first thing to do is to define a report group via the “View/Report Groups” menu (see Figure 12).

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

Reports with Charts

In JasperReports 1.0.1 and iReport 0.5.1, you can design reports with charts. Suppose you want to add a pie chart that shows the relative salary costs of each service to the end of your report. You would have to put it in the Summary section. You may need to enlarge it a bit so that a decent-sized graph can fit. Then add a new chart in this section using the “Edit/Insert Element/Chart” menu item or the “Chart tool” icon. Choose a pie chart.

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:

  • Key Expression: Identifies each slice. Enter “$F{serv_name}” for each slice to represent a service.
  • Value Expression: Enter “$V{service_salary_subtotal}” to associate the total salary cost of each service.
  • Label Expression: The label to display for each slice. Enter “$F{serv_name}” to display the service name.

Now run the report. You should get a pie chart at the end of your report (see Figure 17).

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:

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 parametersMap 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 connectionConnection 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.

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:

  • Eclipse BIRT is a new, up-and-coming charting and reporting tool with a nice Eclipse plugin. Although a relative newcomer, it has some powerful reporting and charting functionalities. On the other hand, it is less mature than JasperReports, and it seems less well integrated with Java It also relies on internal JavaScript scripting for report enhancing. Integration with datasources other than a plain JDBC connection seems to be complicated as well. Nevertheless, it is worth a look.
  • 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 JasperReports?without comprising its power. Together, they form an impressive pair. Try it out!

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may