Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to make reports using Jasper Reports and Java

JasperReports is one of the most popular and widely used open source reporting engines. This is completely developed using java and related libraries. In this article, we will talk about JasperReports library and also discuss how to use it.

JasperReports is one of the most popular and widely used open source reporting engines. This is completely developed using java and related libraries. It has the ability to use data coming from any type of data source and can produce formatted reports.

In this article, I will talk about JasperReports library and also discuss how to use it.

JasperReports is an open source Java based reporting tool which can write outputs to a wide range of targets e.g. screen, a printer, a PDF file, an HTML page, Microsoft Excel, RTF, ODT, Comma-separated values or even in XML formats. It is widely used in Java-based applications, which includes Java EE or web applications, in order to generate dynamic content. Instructions to generate the reports are stored in an XML or a .jasper file which the tool reads and produces the output in desired format.

Getting started with JasperReports

In order to setup JasperReports, we need the following two up and running -

  • JDK Version 1.6 or higher
  • JDBC Driver Version 2.1

Installation -

  • Step 1 - JasperReports comes as a .jar library file. Installation is very simple. We just need to add the jar file in the classpath environment variable.
  • Step 2 - Download and install Ant from the Apache website. Ant will be used to compile the source files, build the distribution, generate Java docs and run the sample application
  • Step 3 - Start the sample database by simply typing the following -

ant runServer

In case you are on windows 7, you need to open the command prompt in administrator mode.

Features of JasperReports

JasperReports come with an array of features. The most important ones are listed below -

  • It has a flexible report layout.
  • It can represent data both textually and graphically.
  • Developers are free to supply data in multiple ways.
  • It has the ability to accept data from multiple data sources.
  • It can generate watermarks on the report pages.
  • It can generate sub reports of the master report.
  • It is capable of exporting reports to an array of formats.

Inside Jasper Reports Library

In the Jasper Reports library, there are different classes for different purpose. E.g there are classes which are used to -

  • compile a JRXML report design
  • fill a report, to print a report
  • export to PDF, HTML and XML files
  • view the generated reports and the report design.

These classes are listed under -

  • net.sf.jasperreports.engine.JasperCompileManager: This is used to compile a JRXML report template.
  • net.sf.jasperreports.engine.JasperFillManager: This is used to fill a report with data from a datasource
  • net.sf.jasperreports.engine.JasperPrintManager: This class is used to print the documents generated by the JasperReports library
  • net.sf.jasperreports.engine.JasperExportManager: This class is used to fetch the PDF, HTML, or XML content for the documents produced by the report-filling process
  • net.sf.jasperreports.view.JasperViewer: This class represents a simple Java Swing application which can load and display reports.
  • net.sf.jasperreports.view.JasperDesignViewer: This class is used at design time to preview the report templates.

Life Cycle of Jasper Reports

The following flow chart clearly describes the life cycle of Jasper Reports -

Figure 1: Life Cycle of Jasper Reports

As shown above, Jasper Reports Life cycle goes through the following phases -

  • Designing the report - This is the first step where we create the JRXML file. JRXML file is a simple XML document which defines the report layout. This file can be developed using any text editor or iReportDesigner is used to create this file manually. If we use iReportDesigner we can visualize the layout of the report and thus the real structure of the JRXML can be ignored.
  • Compiling the report - In this step the JRXML which is built in step 1 is compiled and a binary object called the Jasper file (file with jasper xtn) is generated. This compilation is done in order to have a better performance while execution. These generated Jasper files are required to be shipped along with your application in order to run the reports.
  • Executing the report (Filling data into the report) - In this step the data from the application is picked and filled in the compiled report format. There is a class net.sf.jasperreports.engine.JasperFillManager which provides necessary functions to fill the data in the reports. Output of this step is a Jasper print file (file with jprint xtn) which can be used either to print or export the report.
  • Exporting the report to desired format - This is the last step where we can export the Jasper print file which is created in the earlier step in to any format using the class JasperExportManager. Since Jasper provides multiple formats of exports, we can use the same input to create multiple representations of the data.

Creating the Report Template file

The report template file or the JRXML file used in JasperReports is a simple XML file having jrxml extension. This XML file contains the tag as its root element. This root element in turn contains multiple sub-elements all of which are optional. JasperReport framework has the ability to handle different types of data sources. In this document we will see how to generate a basic report, by just passing a collection of Java data object or a POJO. Here we will use Java beans. The final report will show Name, City, State and Country of a list of people. The report template is designed and created in following two steps –

  • Step 1 Creating the JRXML file.
  • Step 2 Previewing the report template.
Let us create our first JRXML file. This file looks like -

Listing 1: The JR XML File

<?xml version = "1.0" encoding = "UTF-8" ? >
  <!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd" >
  <jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
  name = "jasper_report_template" language = "groovy" pageWidth = "595" pageHeight = "842" columnWidth = "555" leftMargin = "20" rightMargin = "20" topMargin = "20" bottomMargin = "20" >
      <queryString >
               <![CDATA[]] >
      </queryString >
      <field name = "country" class = "java.lang.String" >
          <fieldDescription > <![CDATA[country]] >  </fieldDescription >
      </field >
      <field name = "state" class = "java.lang.String" >
          <fieldDescription > <![CDATA[state]] > </fieldDescription >
      </field >
      <field name = "city" class = "java.lang.String" >
          <fieldDescription > <![CDATA[state]] > </fieldDescription >
      </field >
      <field name = "country" class = "java.lang.String" >
          <fieldDescription > <![CDATA[country]]> </fieldDescription >
      </field >
      <field name = "name" class = "java.lang.String" >
          <fieldDescription > <![CDATA[name]]> </fieldDescription >
      </field >
      <columnHeader >
               <band height = "23" >
                      <staticText >
                             <reportElement mode = "Opaque" x = "0" y = "3" width = "535" height = "15" backcolor = "#70A9A9" />
                             <box >
                                    <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" />
                             </box >
                             <textElement />
                             <text > <![CDATA[]] > </text >
                      </staticText >
                      <staticText >
                             <reportElement x = "414" y = "3" width = "121" height = "15" />
                             <textElement textAlignment = "Center"
                                    verticalAlignment = "Middle" >
                             <font isBold = "true" />
                             </textElement >
                             <text > <![CDATA[Country]] > </text >
                      </staticText >
                      <staticText >
                             <reportElement x = "414" y = "3" width = "121" height = "15" />
                             <textElement textAlignment = "Center"
                                    verticalAlignment = "Middle" >
                             <font isBold = "true" />
                             </textElement >
                             <text > <![CDATA[State]] > </text >
                      </staticText >
                      <staticText >
                             <reportElement x = "414" y = "3" width = "121" height = "15" />
                             <textElement textAlignment = "Center" verticalAlignment = "Middle" >
                             <font isBold = "true" />
                             </textElement >
                             <text > <![CDATA[City]] > </text >
                      </staticText >
                      <staticText >
                             <reportElement x = "0" y = "3" width = "136" height = "15" />
                             <textElement textAlignment = "Center" verticalAlignment = "Middle" >
                             <font isBold = "true" />
                             </textElement >
                             <text > <![CDATA[Name]]> </text >
                      </staticText >
               </band >
         </columnHeader >
         <detail >
               <band height = "16" >
                      <staticText >
                             <reportElement mode = "Opaque" x = "0" y = "0" width = "535" height = "14" backcolor = "#E5ECF9" />
                                    <box >
                                          <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" />
                                    </box >
                             <textElement />
                             <text >      <![CDATA[]]> </text>
                      </staticText >
                      <textField >
                             <reportElement x = "414" y = "0" width = "121" height = "15" />
                                    <textElement textAlignment = "Center" verticalAlignment = "Middle" >
                                          <font size = "9" />
                                    </textElement >
                                    <textFieldExpression class = "java.lang.String" >
                                          <![CDATA[$F{country}]] >
                                    </textFieldExpression >
                      </textField >
                      <textField >
                             <reportElement x = "414" y = "0" width = "121" height = "15" />
                                    <textElement textAlignment = "Center" verticalAlignment = "Middle" >
                                          <font size = "9" />
                                    </textElement >
                                    <textFieldExpression class = "java.lang.String" >
                                          <![CDATA[$F{state}]] >
                                    </textFieldExpression >
                      </textField >
                      <textField >
                              <reportElement x = "414" y = "0" width = "121" height = "15" />
                              <textElement textAlignment = "Center" verticalAlignment = "Middle" >
                                    <font size = "9" />
                              </textElement >
                              <textFieldExpression class = "java.lang.String" >
                                     <![CDATA[$F{city}]] >
                             </textFieldExpression >
                      </textField >
                      <textField >
                             <reportElement x = "0" y = "0" width = "136" height = "15" />
                             <textElement textAlignment = "Center" verticalAlignment = "Middle" />
                             <textFieldExpression class = "java.lang.String" >
                                    <![CDATA[$F{name}]] >
                             </textFieldExpression >
                      </textField >
          </band >
      </detail >
  </jasperReport >

The above file is a simple JR XML file which contains the following major tags -

  • : This holds the query which is used to fetch data. In our case, this is empty since we are passing data via Java Beans. This tag usually contains the SQL statement which is used to retrieve the report result.
  • : This tag maps the data from the datasources or queries into the report templates.
  • : This tag maps the field name with the exact element in the XML file.
  • : This tag defines a static text which is not dependant on any datasource, variable, parameter or other report expression.
  • : This tag defines how the result field would appear.
  • $F{country}: This is a variable which holds the value of the predefined field in the tag .
  • : Band is the tag which contains the actual data that is displayed in the report.

Previewing the Report Template

In order to preview the report template file, we need to execute the utility - net.sf.jasperreports.view.JasperDesignViewer which is available in the JasperReports JAR library. This utility helps in previewing the report design without having to compile it or fill it. This is a standalone Java application and hence can be executed using the java command or using an ant script. Before executing this application, make sure to have the following libraries in the system classpath -

  • commons-logging-1.2.jar
  • commons-digester-1.6.jar
  • commons-collections-3.2.1.jar
  • commons-beanutils-1.8.3.jar

Execute the above mentioned application as under -

java net.sf.jasperreports.view.JasperDesignViewer &lt;PATH TO JRXML FILE&gt;

Once executed, the report template should come out as below –


Figure 2: The report template preview

Here we see that only the report expressions used to fetch the actual data is shown out since at this stage we don't have access to the real time data.

Compiling the Report Template file

The above JRXML file needs be compiled into JasperReport Binary format which is called the jasper file. The interface net.sf.jasperreports.engine.design.JRCompiler which is part of the jasperreport library plays a vital role in compilation of this report template file. Implementation of this interface can be written in Java, Groovy, JavaScript or any other scripting language. We can compile JRXML file in the following two ways:

  • Programmatic compilation.
  • Compilation through ANT task.

In our article we will compile the JRXML file using the programmatic compilation approach. Let us write a Java program as under –

Listing 2: Java class to compile the JRXML template

package com.home.jasper;
  import net.sf.jasperreports.engine.JRException;
  import net.sf.jasperreports.engine.JasperCompileManager;
   
  public class JasperReportCompiler {
   
     public static void main( String[] args ) {
        String sourceFileName = "E://work//jasperreports-6.0.4//tests//PeopleData.jrxml";
   
        System.out.println(  "Compiling Report Design ..." );
        try {
           /**
            * Compile the report to a file name same as
            * the JRXML file name
            */
           JasperCompileManager.compileReportToFile( sourceFileName );
        } catch (JRException e) {
           e.printStackTrace();
        }
        System.out.println( "Done compiling!!! ..." );
     }
  }

Before executing this java file make sure that the language in your JRXML file is set to Java. The default language is set to groovy in this file. Once the compilation is over successfully, we can see a jasper file is generated in the same location where the JRXML file is saved. We can use this jasper file to preview our report as under –

java net.sf.jasperreports.view.JasperDesignViewer E:\work\jasperreports-6.0.4\tests\jasper_report_template.jasper

It should be noted that here we are using the jasper file as a parameter while earlier we were using the JRXML file as a parameter. Once executed, we can see the same report design as shown in Figure 3.

Filling the Reports

The goal of any reporting tool is to produce high standard documents. The report filling process helps the reporting tool to achieve this by manipulating the datasets. The following main inputs are required in this process -

  • Report Template: This is actual JasperReport file or the JRXML file
  • Report Parameters: These are the named values which are passed at the time of filling the report to the engine.
  • Data Source: The Jasper file can be filled from a wide range of datasources e.g an SQL query, an XML file, a csv file, an HQL or Hibernate Query Language or even a collection of Java Beans.

The output of this process is file with .jrprint xtn which is ready to be viewed, printed or exported to other formats. Here, the facade class - 'net.sf.jasperreports.engine.JasperFillManager' is used to fill a report template with data. The JasperFillManager' class contains many fillZZZZ() methods which are used to fill report templates. These templates can be sourced from -

  • the disk
  • any sort of input stream or
  • can be supplied directly as in-memory.

If we have a close look in the 'JasperFillManager' class we can figure out that there are two categories of fillReportXXX() methods in this facade as under :

  • The first category has a java.sql.Connection object as one of its parameter since most of the times the reports are filled with data from a relational database. This is done in following two steps -
    • Connect to the database using the JDBC driver.
    • Add the SQL query inside the report template.

The JasperReports engine uses this JDBC connection and executes the SQL query. The result of this is then provided for filling the report.

  • In the second category, we have a datasource object of type - 'net.sf.jasperreports.engine.JRDataSource' which is used to fill the data when available in the forms.

Now, let us write a Plain Old Java Object or a POJO, 'PeopleDataBean.java' which represents the data object globally known as Java Beans. This class defines the following String objects -

  • name
  • city
  • state and
  • country

This class is shown below -

Listing 3: POJO Class – PeopleDataBean

package com.home.jasper;
public class PeopleDataBean {
 
       private String name;
       private String city;
       private String state;
       private String country;
 
       public String getName () {
             return name;
       }
 
       public void setName ( String name ) {
             this.name = name;
       }
 
       public String getCity () {
             return city;
       }
 
       public void setCity ( String city ) {
             this.city = city;
       }
 
       public String getState () {
             return state;
       }
 
       public void setState ( String state ) {
             this.state = state;
       }
 
       public String getCountry () {
             return country;
       }
 
       public void setCountry ( String country ) {
             this.country = country;
       }
}

Our next step is to write a class 'PeopleDataBeanList.java'. This class has the business logic which is used to generate a collection of java bean objects. This object is then passed to the Jasper report engine which finally generates the report. In our example, we are adding four DataBean objects in the List. This class is shown as under -

Listing 4: The Bean list class

package com.home.jasper;

import java.util.ArrayList;

public class PeopleDataBeanList {

public ArrayList getDataBeanList() {

ArrayList dataBeanList = new ArrayList();

dataBeanList.add(produceData ("Manisha", "North Delhi", "Delhi", "India"));

dataBeanList.add(produceData ("Dennis Ritchie", "Sacramento", "California", "USA"));

dataBeanList.add(produceData ("V.Anand", "Chennai", "Tamil Nadu", "India"));

dataBeanList.add(produceData ("Parvez", "Upton Park", "London", "UK"));

return dataBeanList;

}

/**

* This method returns a DataBean object, with name, city, state and country set in it.

*/

private PeopleDataBean produceData(String name, String city, String state, String country) {

PeopleDataBean dataBean = new PeopleDataBean();

dataBean.setName(name);

dataBean.setCity(city);

dataBean.setState(state);

dataBean.setCountry(country);

return dataBean;

}

}

Next, we write a main class file PeopleDataReportFiller.java. This class gets the java bean collection from the PeopleDataBeanList class and passes it to the Jasper report engine, which then fills the report template. This class is shown below -

Listing 5: The main class - used to fill report

package com.home.jasper;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
 
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
 
public class PeopleDataReportFiller {
       @SuppressWarnings("unchecked")
       public static void main(String[] args) {
             String sourceFileName = "E://work//jasperreports-6.0.4//tests//jasper_report_template.jasper";
             PeopleDataBeanList peopleDataBeanList = new PeopleDataBeanList();
             ArrayList<PeopleDataBean> dataList = peopleDataBeanList.getDataBeanList();
 
             JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList);
 
             Map parameters = new HashMap();
             try {
                    JasperFillManager.fillReportToFile(sourceFileName, parameters, beanColDataSource);
             } catch (JRException e) {
                    e.printStackTrace();
             }
       }
}

Once we execute this class, we get a .jsprint file in the same location where the .jasper file is generated. Our next job is to view the report and finally export it to any desired format. In order to view the report in the default format, we need to execute the following command on the command prompt -

java net.sf.jasperreports.view.JasperViewer <PATH TO THE .jrprint file>. 

This generates the report in the default format as under -

Figure 3: The generated report in default format

Printing and exporting the report

In order to print the report, let us modify our existing class - ' PeopleDataReportViewer' and have a new class ' PeopleDataReportPrinter'. In this class we use the JasperPrintManager.printReport() method. This method takes the source file name which is the .jrprint file which we generate in the earlier step. This method has another parameter which is boolean. This is used for displaying the standard print dialog - we set it to true in our case. This class is as under -

Listing 6: The main class - used to print report

package com.home.jasper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
 
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrintManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
 
public class PeopleDataReportPrinter {
       @SuppressWarnings("unchecked")
       public static void main(String[] args) {
             String sourceFileName = " E://work//jasperreports-6.0.4//tests//jasper_report_template.jasper ";
             String printFileName = null;
             PeopleDataBeanList peopleDataBeanList = new PeopleDataBeanList();
             ArrayList dataList = peopleDataBeanList.getDataBeanList();
 
             JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList);
 
             Map parameters = new HashMap();
             try {
                    printFileName = JasperFillManager.fillReportToFile(sourceFileName, parameters, beanColDataSource);
                    if(printFileName != null){
                           JasperPrintManager.printReport(printFileName, true);
                    }
             } catch (JRException e) {
                    e.printStackTrace();
             }
       }
}

On executing this class, a print dialog box appears. Click on the Ok button to print the document.

In order to export the report, we write a main class - PeopleDataReportExporter which gets the java bean collection from the class PeopleDataBeanList and passes it to the Jasper report engine, to fill the report template. Here we will use the ' JasperExportManager.exportReportXXXXX' to export the report in the desired format. This class is shown as under –

Listing 7: The report exporter class

package com.home.jasper;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
 
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRXlsExporter;
 
public class PeopleDataReportExporter {
       @SuppressWarnings("unchecked")
       public static void main(String[] args) {
             String sourceFileName = "E://work//jasperreports-6.0.4//tests//jasper_report_template.jasper";
             String printFileName = null;
             PeopleDataBeanList peopleDataBeanList = new PeopleDataBeanList();
             ArrayList dataList = peopleDataBeanList.getDataBeanList();
             JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList);
 
             Map parameters = new HashMap();
             try {
                    printFileName = JasperFillManager.fillReportToFile(sourceFileName, parameters, beanColDataSource);
                    if (printFileName != null) {
                           /**
                           * 1- export to PDF
                           */
                           JasperExportManager.exportReportToPdfFile(printFileName, "E://work//jasperreports-6.0.4//tests//PeopleData.pdf");
 
                           /**
                           * 2- export to HTML
                           */
                           JasperExportManager.exportReportToHtmlFile(printFileName, "E://work//jasperreports-6.0.4//tests//PeopleData.html");
                    }
             } catch (JRException e) {
                    e.printStackTrace();
             }
       }
}

Before executing this class, make sure to have the following libraries in your classpath -

  • com.lowagie.text-2.1.7.jar
  • com.fasterxml.jackson.databind.jar
  • com.fasterxml.jackson.core.jar

Once you execute this class, the following two files will be generated -

  • PeopleData.pdf
  • PeopleData.html

Conclusion

Throughout this document we have seen how to generate a simple report using JasperReports framework. Once generated, we can export it into any format of our choice. Let us conclude our discussion in the following bullets -

  • JasperReports is an open source Java based reporting tool.
  • This tool can be used to write outputs to a wide range of targets e.g. screen, a printer, a PDF file, an HTML page, Microsoft Excel, RTF, ODT, Comma-separated values or even in XML formats.
  • In order to setup JasperReports, we need the following two properly setup and running -
    • o JDK Version 1.6 or higher
    • o JDBC Driver Version 2.1
  • · Following are the major components of jasper reports -
    • o Jasper Compile Manager
    • o Jasper Export Manager
    • o Jasper Print Manager
  • · Jasper Report life cycle goes through the following phases -
    • o Designing the report.
    • o Compiling the report.
    • o Executing the report.
    • o Exporting the report.

I have tried to cover most of the aspects of Jasper as a reporting tool. I hope you have enjoyed reading this article.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login