Monday, October 12, 2009

JASPER REPORT

Generating reports is a common, if not always glamorous, task for programmers. In the past, report generation has largely been the domain of large commercial products such as Crystal Reports. Today, the open source JasperReports report generating library gives Java developers a viable alternative to commercial software.

The open source JasperReports uses XML templates for your reporting needs

JasperReports provides the necessary features to generate dynamic reports, including data retrieval using JDBC (Java Database Connectivity), as well as support for parameters, expressions, variables, and groups.

Note: The documentation and code featured in this article are based on JasperReports version 0.3.3.


Architecture

As shown in the above figure JasperReports architecture is based on declarative XML files which by convention have an extension of jrxml that contains the report layout. A lot of third-party design tools were produced to generate your jrxml file in a smooth way (like iReport or JasperAssistant) Design file is supposed to be filled by report's result which is fetched from database, XML files, Java collection, Comma-separated values or Models. Jasper can communicate with those data-sources and more, it can merge any number of data-sources together and manipulates the results of any combinations. This communication goes through JDBC, JNDI, XQuery, EJBQL, Hibernate or existing Oracle PL/SQL. You also can define your own data-source class and pass it to jasper engine directly. After defining your report design layout in jrxml format and determining your data source(s) jasper engine does the rest of work. It compiles your design file and fills it with results fetched from data-source and generates your report to the chosen exporting format (PDF, Excel, HTML, XML, RTF, TXT …, etc.)


Report Definition file structure (jrxml):

Jasper design file –jrxml- contains the following elements:
  • - the root element.
  • - its contents are printed at the beginning of every page in the report.
  • - contains the body of the report, repeated by n number of results
  • - its contents are printed at the bottom of every page in the report.
  • - defines a report section, all of the above elements contain a band element as its only child element.

Only the root element is mandatory, the rest of elements are optional.


Environment

To set up working environment we need to download JasperReport jar file from the following URL: http://sourceforge.net/project/showfiles.php?group_id=36382&package_id=28579
And add the following jars to your project classpath:
  • jasperreports-2.0.4.jar
  • commons-digester-1.7.jar
  • commons-collections-2.1.jar (commons-collections.jar)
  • commons-logging-1.0.2.jar
  • commons-beanutils.jar
  • iText-2.0.7.jar (used infor PDF exporting

Sample Application

At this section we'll introduce a sample application that generates PDF, HTML and Excel files contain the results of our report which is built over Oracle database contains the following table:
ITEM

ITEM_ID ---- NUMBER(5) --- NOT NULL
CATEOGRY_ID ---- NUMBER(5) --- NOT NULL
ITEM_NAME ---- VARCHAR2(50) --- NOT NULL
ITEM_DESCIPTION ---- VARCHAR2(200)

ITEM_AMOUNT ---- NUMBER(5) ---- NOT NULL

Result: Report should retrieve the items with amount less than or equal 100 item.

We're going to divide the work into two steps:

  1. Generate the report design (jrxml file).
  2. Implement application that assigns data source, compiles jrxml file and exports result in the chosen format.


Designing The Report

First we create new text file and rename it to sample_report.jrxml, this file should contain the following XML tags.

01.
02."//JasperReports//DTD Report Design//EN"
04.
05.<jasperReport name="sample_report" >
06.<queryString>
07.
09.queryString>
10.<field name="ITEM_NAME" class="java.lang.String"/>
11.<field name="ITEM_AMOUNT" class="java.math.BigDecimal"/>
12.<columnHeader>
13.<band height="28" isSplitAllowed="true">
14.<staticText>
15.<reportElement x="40" y="11" width="193" height="15" key="staticText-1"/>
16.<text>
17.
18.text>
19.staticText>
20.<staticText>
21.<reportElement x="330" y="11" width="193" height="15" key="staticText-2"/>
22.<text>
23.
24.text>
25.staticText>
26.band>
27.columnHeader>
28.
29.<detail>
30.<band height="27" isSplitAllowed="true">
31.<textField>
32.<reportElement x="47" y="6" width="173"
33.height="18" key="textField"/>
34.<textFieldExpression class="java.lang.String">
35.
36.textFieldExpression>
37.textField>
38.<textField >
39.<reportElement x="330" y="6" width="100"
40.height="18" key="textField"/>
41.<textFieldExpression class="java.math.BigDecimal">
42.
43.textFieldExpression>
44.textField>
45.band>
46.detail>
47.jasperReport>

The above XML file consists of the following main sections that defining report behavior and layout:

  • : contains the SQL statement which retrieves the report result.
  • : defines the resulted fields from the query, and give them name to reuse them into the report body [they are case-sensitive].
  • : contains the header titles "Item Name" in tag format.
  • : defines the appearance of result field.
  • $F{ITEM_NAME}: is a variable contains the value of Query result predefined field in the tag .

Once we finished the report design file, save it in C:\ directory.

Implementing The Report Service:

- Create a new java project.
- Import the jars listed in environment section to your project libraries.
- Create new class and import the following packages

01.import java.sql.Connection;
02.import java.sql.DriverManager;
03.import java.sql.SQLException;
04.import java.util.HashMap;
05.
06.import net.sf.jasperreports.engine.JRException;
07.import net.sf.jasperreports.engine.JRExporterParameter;
08.import net.sf.jasperreports.engine.JasperCompileManager;
09.import net.sf.jasperreports.engine.JasperExportManager;
10.import net.sf.jasperreports.engine.JasperFillManager;
11.import net.sf.jasperreports.engine.JasperPrint;
12.import net.sf.jasperreports.engine.JasperReport;
13.import net.sf.jasperreports.engine.export.JRXlsExporter;


- Define the data source, in my case it's an oracle connection and established by JDBC as following:

01.public static Connection establishConnection()
02.{
03.Connection connection = null;
04.try
05.{
06.Class.forName("oracle.jdbc.driver.OracleDriver");
07.String oracleURL = "jdbc:oracle:thin:@localhost:1521:mySID";
08.connection = DriverManager.getConnection(oracleURL,"username","password");
09.connection.setAutoCommit(false);
10.}
11.catch(SQLException exception)
12.{
13.exception.printStackTrace();
14.}
15.return connection;
16.
17.}

Finally, the core code for compiling, filling and exporting the results in the following sequence:

- Define jasper objects that will hold report template, compiled files, and result files.

1./* JasperReport is the object
2.that holds our compiled jrxml file */
3.JasperReport jasperReport;
4.
5.
6./* JasperPrint is the object contains
7.report after result filling process */
8.JasperPrint jasperPrint;

- Create a connection to my data-source; initialize the report parameter into empty HashMap then compile our jrxml file into JasperReport object and finally fill the JasperPrint object by data from data-source connection.

01.// connection is the data source we used to fetch the data from
02.Connection connection = establishConnection();
03.// jasperParameter is a Hashmap contains the parameters
04.// passed from application to the jrxml layout
05.HashMap jasperParameter = new HashMap();
06.
07.// jrxml compiling process
08.jasperReport = JasperCompileManager.compileReport
10.
11.// filling report with data from data source
12.
13.jasperPrint = JasperFillManager.fillReport(jasperReport,jasperParameter, connection);

- Last segment of code is responsible for exporting the result files into different formats

01.// exporting process
02.// 1- export to PDF
03.JasperExportManager.exportReportToPdfFile(jasperPrint, "C://sample_report.pdf");
04.
05.// 2- export to HTML
06.JasperExportManager.exportReportToHtmlFile(jasperPrint, "C://sample_report.html" );
07.
08.// 3- export to Excel sheet
09.JRXlsExporter exporter = new JRXlsExporter();
10.exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
11.exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "C://simple_report.xls" );
12.
13.exporter.exportReport();

You have just managed to generate your first jasper report in 3 different file formats at C:\\ directory (shown in the image below):

- sample_report.html
- sample_report.pdf
- sample_report.xls


Here we reach the end of today's article, next article we will cover the following points:
1- Using design tool (iReport) to generate robust and smooth jrxml file.
2- Create run-time search criteria and pass them to report.

Note: this Article was first published in FCI-H Blog, here

References:
http://www.jasperforge.org/jaspersoft/opensource/business_intelligence/jasperreports/index.html
http://en.wikipedia.org/wiki/Jaspersoft
http://www.javaworld.com/javaworld/jw-09-2002/jw-0920-opensourceprofile.html


2 comments: