01: JasperReports with iReport tutorial

JasperReports is a popular reporting framework/tool to produce reports in PDF, XLS, etc.

Step 1: Define a Person.java POJO class as defined below. This is the Java bean data source that is going to provide the data to the report.

Step 2: Download Jaspersoft iReport 5.0.0, and execute the  ireport.exe from the iReport folder (e.g. C:\ireport\5.0.0\iReport-5.0.0\bin). You need to design the template now using iReport 5.0.0 and generate the person-template.jrxml, which will be used in Java as the template to generate the report.

Step 3: Tell iReport where to find the classes by defining the class path via Tools –> Option, and then select the “Classpath” tab.

Step 4: Create a new report via File –> New.

provide the name and path where you want to generate the template jrxml file.

Click on “Next” and then “Finish” to get the designer screen where you can add labels and text fields for the report.

Step 5: Add the column header for the report by dragging and dropping the “Static Text” for the column headers.

Step 6: Before you can map the Text Field with bean data source values, you need to bring in the Person java class we created in Step 1.Click on the little data source icon as shown below to get the pop up that allows you to define the com.mycompany.app.jasper.Person bean and select the firstName, surname, and age and select on “Add selected fields” and then click on “OK“.

Step 7: Now you can map these fields to the new “Text Field” that you drag and drop as shown below. This will be done in the “detail1” section.

Step 8: Now, you need to map each Text Field to the corresponding fields of Person.java. You do this by Right-clicking and selecting “Edit expression” on the field.

Step 9: In the “expression editor”, you can map the field. Remove the default $F{Field} and “double-click” on “firstName” to get $F{firstName} and click on “Apply” as shown below. 

Step 10: Map all the fields as shown below, and click on the icon that compiles the design to generate the person-template.jrxml (text) and person-template.jasper (binary) files. If there are any compile errors, you need to fix it and re-compile. You only need the jrxml file to generate report in Java.

Step 11: Before you write the Main.java class, you need to have the relevant Jasper jar files. Here is the pom.xml file with the relevant dependency jar files. 

Step 12: Finally the Main.java that generates the report by combining the layout template person-template.jrxml and the data by executing the Main class.


Finally, the report produced looks like

Note: iText jar is required to generate PDF reports. If you want to generate excel report, you need additional dependency jar like POI.


Java Interview FAQs

800+ Java Interview Q&As

Top