Jasper Reports and Data Sources

Introduction

Jasper Report is a powerful open source reporting architecture. It is completely written in java and is full of features required for reporting. Following are some of the key features supported.

    also read:

  • Pixel-perfect and page-oriented reports for printing or continuous output for web or print
  • Dashboards, tables, crosstabs, charts and gauges
  • Report output in PDF, XML, HTML, CSV, XLS, RTF, TXT
  • Sub-reports to easily handle highly complex layouts
  • No limit to report size
  • Conditional printing
  • Internationalized and Localizable
  • Visual text rotation
  • Multiple data sources support

In this article the focus will be on the last point; i.e. the Support Jasper Reporting architecture provides for accessing data from various kinds of data sources. We will look into how a developer can use the powerful API support that jasper provides to handle the following types of data sources for creating the reports.

  • Database JDBC connection
  • XML file data source

What is a Data source!?

Before getting into the technical details of how jasper handles different data sources lets first understand what a data source is. Any report; which is an intelligent representation of a result of search/study; will need to show Data[obviously!]

But where does this data come from?

It can either come from the User input or from Data base.

If the report is to be generated purely from what the user has entered and not from the data present in database; then there is NO requirement of data source. Generally reports are made from a query on data which has been saved for future use in a persistence data storage.[database/flat/xml file etc..]

Jasper Reporting is a template based architecture where the template file stores the report layout and data is later filled into this layout. The template file is a an xml file [.jrxml] and is holds the design of the report; data is provided to the complied layout [.jasper java object] and the jasper engine creates the report.

image sourced from :http://ireport.sourceforge.net/cap3.html

Software Requirements

For this Sample application i have used the following software’s.

  • JDK 1.6
  • iReport 3.0.0[or higher]
  • Netbeans IDE 6.5
  • Acrobat PDF reader
  • Jasper Report API jars

Setting up everything

Download and install JDK1.6,Netbeans IDE and iReport.

Start netbeans and create a Java Application project.

Jasper Report API Jars

Please download the following Jar files and import them in the library of the newly created java application project.


Note: All these jars will be present in the lib directory of the iReport.

Using a Database with JDBC connection

Data from a database can be converted to a report using jasper API in two ways.

  • Using iReport tool alone.
  • Using iReport for designing and using the design in a java program for report creation.

note: Assumption made is that the user already has an installed database.

Using a Database [JDBC connection] : Creating report suing iReport alone

Let’s create a report which reports employee information stored inside a table. The table has 3 fields and 3 rows of data stored.

Following are the steps needed to get the report generated from the iReport tool.

  1. Create a database connection so that iReport can us it to create the report
    • Open the Wizard [Data > Connections/DataSources]

  2. Create a template which reports 3 fields for report

  3. Note: The Report has

    • A reportQuery is embedded into the report [Data > Report Query]

    • 3 defined Fields [EID,ENAME,ESALARY] this should be same as the column names [Or alias used in the ReportQuery]
    • 3 defined Fields [EID,ENAME,ESALARY] are placed in the detail band of the report[ EID is the selected TextField ]
    • All the other bands are made to nonexistent [Band height=0]
    • Finally Run the Report

    Click the button marked in red circle

    The output will look like[assuming that the preview selected is PDF]

    Congrats you have your first Report from database!!.

Using a Database [JDBC connection] : Creating report suing iReport alone

We will be using the same table to retrieve data from and the template created for the earlier sample for generating the report.[Step 2]

And our Java Code will look like the following

import java.sql.Connection;
import java.io.FileNotFoundException;
import java.sql.DriverManager;
import java.util.HashMap;
import net.sf.jasperreports.engine.*;

public class JasperJDBCConnection {

    public static void main(String[] args) throws FileNotFoundException, JRException {
        JasperReport jasperReport = null;
        String path = "D:/JasperTemplates/";
        JasperPrint jasperPrint = null;

        //Gettign the connection object
        Connection conn = getConnection();

        //Provide path for your JRXML template.
        String templateName = path + "ReportSQL.jrxml";

        //Provide path for your final pdf file.
        String destinationFile = path + "ReportSQL.pdf";

        //Compiling the template.
        jasperReport = JasperCompileManager.compileReport(templateName);

        //Sending a parameter with the logged in user name as value
        HashMap parameters = new HashMap();

        // Filling the report template with data
        jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);

        //Sending a Complete print of the report.
        JasperPrintManager.printReport(jasperPrint, true);

        //Exporting it to an PDF
        JasperExportManager.exportReportToPdfFile(jasperPrint, destinationFile);

    }
  //Getting the JDBC Connection object to be used in the template.The data base used for the sample is MYSQL running on localhost at port 3306
    public static Connection getConnection() {
        Connection conn = null;
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "testjasper";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "root";
        String password = "";
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url + dbName, userName, password);
            System.out.println("Connected to the database");
        } catch (Exception e) {
            e.printStackTrace();
        }
		
        return conn;
		
    }
}

Brief explanaition of the code.

  1. ReportSQL.jrxml is the name of the JRXML template.
  2. ReportSQL.pdf is the output pdf file.
  3. getConnection() is a utility method used to get the connection object that is later used for retrieving data from the database. “testjasper” refers to the MYSQL data base running on the localhost port 3306.
  4. JasperCompileManager.compileReport() takes in the template file and converts it into a jasper object. This is later used by the reporting engine to create the report.
  5. JasperFillManager.fillReport() uses the compiled template [jasper object] ,hashmap[a dummy: ideally used to pass parameters],and the connection object created to Fill the report.
    The Connection object is used by the Jasper Reporting engine to fire the Report Query and get the data that is required to be filled in the report.
  6. Finally the Report is exported to a PDF file using the JasperExportManager.exportReportToPdfFile() method
    Output will be exactly the same; since we are using the same data and the template. The only diffrence we are making is instead of iReport invoking the Jasper Api’s internally we are doing it programmatically.
  7. XML file data source
    Lets now focus on using XML flat file as a data source instead of using a fully fledged data base.
    This feature allows jasper Report to integrate with non java applications which provide the xml data that needs to be reported.

    In this sample we will be using the same template we created earlier [with slight modifications] and use a static xml file as a data source.

    Our XML file will be:

  8. The change needed in the template file will be for the Fields.
    • The only change is that we added description.
      And our Java Code will look like the following

      import java.io.FileNotFoundException;
      import java.util.HashMap;
      import net.sf.jasperreports.engine.*;
      import net.sf.jasperreports.engine.data.JRXmlDataSource;
      import net.sf.jasperreports.view.JasperViewer;
      
      public class XMLDataSourceSample {
      
          public static void main(String[] args) throws FileNotFoundException, JRException {
              JasperReport jasperReport = null;
              String recordPath = "/employee/person";
              String xmlFileName = "Address.xml";
              String path = "D:/JasperTemplates/";
              JasperPrint jasperPrint = null;
          
              //Provide path for your JRXML template.
              String templateName = path+"ReportXML.jrxml";
      
              //Provide path for your final pdf file.
              String destinationFile = path+"ReportXML.pdf";
      
              //Compiling the template.
              jasperReport = JasperCompileManager.compileReport(templateName);
      
              //Sending a parameter with the logged in user name as value
              HashMap parameters = new HashMap();
              //Creating the datasource
              JRXmlDataSource jrxmlds = new JRXmlDataSource(path+xmlFileName, recordPath);
      
              // Filling the report template with data
              jasperPrint = JasperFillManager.fillReport(jasperReport, parameters,jrxmlds);
      
              JasperViewer.viewReport(jasperPrint);
      
              //Exporting it to an PDF
              JasperExportManager.exportReportToPdfFile(jasperPrint, destinationFile);
      
          }   
      }

      Brief explanation of the code.

      1. ReportXML.jrxml is the name of the JRXML template.
      2. ReportXML.pdf is the output pdf file.
      3. JRXmlDataSource takes in two arguments Path of the xml file with data and the recordPath
      4. JasperCompileManager.compileReport() takes in the template file and converts it into a jaspe object. This is later used by the reporting engine to create the report.
      5. JasperFillManager.fillReport() uses the compiled template [jasper object] ,hashmap[a dummy: ideally used to pass parameters],and the JRXmlDataSource object created from the XML file
      6. Finally the Report is exported to a PDF file using the JasperExportManager.exportReportToPdfFile() meathod

      Output will be exactly the same; since we are using the same data [from the XML] and the template.

      Congrats you have your first Report from an XML programmatically!!.

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*