Original URL: https://www.theregister.com/2006/10/24/jasperreports_tutorial/

Creating a Report with JasperReports

Creating presentation-quality PDF and Excel Reports with an OSS product.

By Deepak Vohra

Posted in Software, 24th October 2006 21:28 GMT

Preparing presentation-quality reports is an everyday occurrence, so any tool that makes the job easier is worth a look. For developers working with Java, one such is JasperSoft’s JasperReports, which is capable of producing a range of outputs, including HTML, PDF, Excel XLS, CSV and XML file formats. The tool can build dynamic presentations from either static data or data retrieved form a database table using an SQL query, and is designed to be integrated directly into Java/J2EE applications.

This tutorial sets out to demonstrate the essentials of how JasperReports can be used. The tool can be used with a variety of Java IDEs, such as Eclipse, and with application servers such as JBoss. In this instance, however, JDeveloper is used because it includes an embedded application server. The examples created are a PDF report and an Excel report.

Preliminary Setup

Download the open source JasperReports tool jar file jasperreports-1.2.7.jar. You will also need to download the iText Java-PDF library itext-1.4.5.jar, the Jakarta-POI zip file poi-bin-2.5.1-final-20040804.zip, and the Commons Digester 1.7 (extract the zip file to a directory).

Then install the JDeveloper 10g IDE Studio Edition Complete Install and Oracle database 10g.

Create an example database table, Catalog; from which you’ll generate your JasperReports report. Create the database table in Oracle SQL *Plus using the SQL script, catalog.sql, which is available in the resources zip file, to create the example table.

Create a JDBC connection to the Oracle database from the JDeveloper IDE. To create a connection select the Connections tab, select the Database node in the Connections Navigator, right click on the Database node, and select New Database Connection. In the Create Database Connection Wizard specify values for the different connection parameters. A connection node gets added to the Connections Navigator as shown in Figure 1. The JDBC connection OracleDBConnection is available as a JNDI resource jdbc/OracleDBConnectionDS. This will be used to retrieve data from the database to generate the JasperReports report.

Figure 1. JDBC Connection

Finally, for now, you’ll also have to download and install Adobe Acrobat Reader.

Installing JasperReports

In this section, a JasperReports project is created in JDeveloper IDE and the libraries required for the JasperReports report are added to the project.

First, select File>New in the JDeveloper IDE. In the New Gallery frame select General in the Categories listed and select Application in the Items listed. Specify an application name in the Create Application frame and a project name in the Create Project frame. A JasperReports application and project get added to the Applications-Navigator (see Figure 2).

Figure 2. JasperReports Project

Next, add the libraries required to generate a JasperReports report to the project. Select the JasperReports project node in the Applications-Navigator and select Tools>>Project Properties. In the Project Properties frame select the Libraries node. Add a library with the Add Library button and add a Jar/Directory with the Add Jar/Directory button. Add the libraries/Jar files listed in the following table.

Project Library/Jar/Zip Description
jasperreports-1.2.7.jar JasperReports API
Commons BeanUtils JavaBeans utility classes
Commons Collections Collections framework extension classes
commons-digester-1.7.jar Classes for processing XML documents.
Commons Logging Logging classes
poi-bin-2.5.1-final-20040804.zip Jakarta POI API to generate an Excel document
itext-1.4.5.jar PDF library
Oracle XML Parser v2 XML parser API

The libraries created are listed in the Libraries frame (see Figure 3). Click on the OK button in the Project Properties frame.

Figure 3. JasperReports Project Libraries

Configuring the JasperReports XML File

The JasperReports report design is specified in a XML configuration file, called catalog.xml in this example, and this is configured for a PDF report in this section. JasperReports XML configuration files are based on the jasperreport.dtd DTD, with a root element of jasperReport. Some of the other elements (with commonly used sub-elements and attributes) in a JasperReports XML file are listed in the following table:

XML Element Description Sub-Elements Attributes
jasperReport Root Element reportFont, parameter, queryString, field, variable, group, title, pageHeader, columnHeader, detail, columnFooter, pageFooter. name, columnCount, pageWidth, pageHeight, orientation, columnWidth, columnSpacing, leftMargin, rightMargin, topMargin, bottomMargin.
reportFont Report level font definitions - name, isDefault, fontName, size, isBold, isItalic, isUnderline, isStrikeThrough, pdfFontName, pdfEncoding, isPdfEmbedded
parameter Object references used in generating a report. Referenced with P${name} ParameterDescription, defaultValueExpression name, class
queryString Specifies the SQL query for retrieving data from a database. - -
field Database table columns included in report. Referenced with F${name} fieldDescription name, class
variable Variable used in the report XML file. Referenced with V${name} variableExpression, initialValueExpression name,class.
title Report title band -
pageHeader Page Header band -
columnHeader Specifies the different columns in the report generated. band -
detail Specifies the column values band -
columnFooter Column footer band -
pageFooter Page footer band -

A band in a report represents a report section. A band element includes staticText and textElement elements. A staticText element is used to add static text to a report (for example, column headers) and a textElement element is used to add dynamically generated text to a report (for example column values retrieved from a database table).

In the following section (headed Generating a JasperReports Report) a JasperReports PDF report and an Excel report are generated from the example Catalog table.

The queryString of the example JasperReports configuration XML file catalog.xml specifies the SQL query to retrieve the data for the report:

<queryString><![CDATA[SELECT CatalogId, Journal,
 Publisher, Edition, Title,
 Author FROM OE.Catalog]]> </queryString>

The reportElement elements specify the ARIAL_NORMAL, ARIAL_BOLD, and ARIAL_ITALIC fonts used in the report. The PDF report has the columns CatalogId, Journal, Publisher, Edition, Title, Author. As usual, the JasperReports configuration file catalog.xml is available in the resources zip file.

Generating a JasperReports Report

The JasperReports classes and interfaces are used to generate a PDF/Excel report from the catalog.xml file. Add an XML file to the JasperReports project with File>New. In the New Gallery frame select General>XML in the Categories listed and XML Document in the Items listed. Specify catalog.xml as the file name in the Create XML File frame. This adds an XML document to the JasperReports project.

Copy the XML document from the resources zip file to catalog.xml. Create a directory C:/JasperReports and save this XML document in the directory.

Now you create a JSP to generate the JasperReports report. Select File>New and in the New Gallery frame select Web Tier>JSP in the Categories listed and select JSP in the items listed. In the Create JSP Wizard specify the JSP file parameters. This adds JSP catalog.jsp to the JasperReports project.

The JDBC data source jdbc/OracleDBConnectionDS must then be configured in the JSP web.xml configuration file. To do this, add the resource-ref element below to the web.xml file:

<resource-ref>
  <res-ref-name>jdbc/OracleDBConnectionDS</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
</resource-ref>

In the catalog.jsp, first import the JasperReports classes and interfaces, as below:

<%@ page
   import="java.io.*,
           java.util.*,
           java.sql.Connection,
           javax.sql.DataSource,
           javax.naming.InitialContext,
           net.sf.jasperreports.engine.*,
           net.sf.jasperreports.engine.design.JasperDesign,
           net.sf.jasperreports.engine.xml.JRXmlLoader,
           net.sf.jasperreports.engine.export.*"
%>

Next, create a InputStream for the JasperReports configuration file catalog.xml and load the XML file:

InputStream input
    = new FileInputStream(new File("C:/JasperReports/catalog.xml"));
JasperDesign design = JRXmlLoader.load(input);

A JasperDesign object represents the report design. Compile the report design file to create a JasperReport object. The compilation of the report design file validates the JasperReports XML file (catalog.xml) with the jaspereports.dtd DTD and converts the report expressions into a ready-to-evaluate form:

JasperReport report = JasperCompileManager.compileReport(design);

Now, obtain a JDBC connection to retrieve data from the database, in order to create your PDF/Excel report:

InitialContext initialContext = new InitialContext();
DataSource ds = (DataSource)initialContext.lookup(
    "java:comp/env/jdbc/OracleDBConnectionDS");
Connection conn = ds.getConnection();

To view this, generate a JasperPrint document, which may be viewed, printed or exported to other formats, from the compiled report design:

JasperPrint print
    = JasperFillManager.fillReport(report, parameters, conn);

The parameters in the fillReport method consist of the parameter values specified in the parameter elements of the XML configuration file. catalog.xml has the parameter ReportTile, so you must specify a value for the ReportTitle parameter:

Map parameters = new HashMap();
parameters.put("ReportTitle", "PDF JasperReport");

A JasperReports report may be exported to a XML file, a PDF file, an HTML file, a CSV file, or an Excel XLS file; to export the JasperReports report we’ve just generated to a PDF file, use this:

OutputStream output
    = new FileOutputStream(new File("C:/JasperReports/catalog.pdf"));
JasperExportManager.exportReportToPdfStream(print, output);

The example JSP file, catalog.jsp, is available in the resources zip file. Copy the code from resources zip file to catalog.jsp in your JDeveloper project.

To run the catalog.jsp JSP, right-click on the catalog.jsp node and select Run (see Figure 4).

Figure 4. Running JasperReports Application

This generates a catalog.pdf PDF file, which may be opened in an Adobe Acrobat Reader as shown in Figure 5.

Figure 5. PDF Report

This PDF report catalog.pdf is also available in the resources zip file.

If a Excel report is required, simply use the JRXlsExporter object to export your JasperReports document to an Excel spreadsheet, specifying an appropriate OutputStream. spreadsheet. So, you can specify a ByteArrayOutputStream for the output from the JRXlsExporter object thus:

OutputStream ouputStream
    = new FileOutputStream(new File("C:/JasperReports/catalog.xls"));
ByteArrayOutputStream byteArrayOutputStream
    = new ByteArrayOutputStream();

Then create a JRXlsExporter object, and set the JasperPrint object from which the report is to be generated and also set the OutputStream, in order to output the report:

JRXlsExporter exporterXLS = new JRXlsExporter();
exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT,
                         print);
exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM,
                         byteArrayOutputStream);

And, export the JasperReports document using:

exporterXLS.exportReport();

Then output the JasperReports Excel report to an .xls file using:

ouputStream.write(byteArrayOutputStream.toByteArray()); 
ouputStream.flush();
ouputStream.close();

The catalog-excel.jsp JSP in the resources zip file is used to generate a Excel spreadsheet similar to the PDF report. The Excel spreadsheet may be opened in MS Excel or Excel Viewer as shown in Figure 6.

Figure 6. Excel Report

The Excel report catalog.xls is available in the resources zip file.

Finally, remember that although the example JasperReports report generated in this tutorial is a PDF/Excel report, as we’ve already pointed out, it could just as easily have been generated as an HTML, XML, or CSV file.