Archive for the ‘Reports’ Category

Jasper Reports Tutorial

Posted: November 23, 2011 in Java, Reports
Tags: , ,

Jasper Reports is one of the most popular and most used open source reporting engine in the industry today. Its completely written in Java and can use data coming from any ‘datasource’  and generate reports in PDF, EXCEL and HTML.

Prerequisites for this tutorial

  1. Download and install iReports from http://jasperforge.org/projects/ireport                      (We use this to create the report template/layout) and this website will give you a  very very clear idea on how to design a report template. Trust me, its easy. It’s easy to understand it from their own website rather me trying to explain it in words.
  2. Download and install MySQL
  3. Have the following jar files in your classpath

commons-beanutils-1.7.jar

commons-collections-3.1.jar

commons-digester-1.8.jar

commons-lang-2.1.jar

commons-logging-1.1.jar

iText-2.1.1.jar

jasperreports-1.0.3.jar

mysql-connector-java-5.0.4-bin.jar

Note: The template that we create using iReport tool will be saved with extension .jrxml

Create a folder jrxml in your project and save/copy the template you designed here.

Create a folder report in your project and this is where your PDF/EXCEL report will be saved

Before we go further, we need to populate the data in the database so that we can fetch it and display it on the report. (Who would like to see a empty PDF report? In case, if you get a empty PDF report, then your must have forgotten to  add iText-2.1.1.jar to the classpath..provided your query works)

Execute the following scripts in MySQL Browser

create table Employee(
ID                 VARCHAR(4) NOT NULL,
First_Name         VARCHAR(10),
Last_Name          VARCHAR(10),
Start_Date         DATE,
End_Date           DATE,
Salary             DECIMAL(8,2),
City               VARCHAR(10),
Description        VARCHAR(15)
)

INSERT into Employee values
(’06’,’Suhas’,’Saheer’,
to_date(‘20071213′,’YYYYMMDD’),
to_date(‘20701213′,’YYYYMMDD’),
52500.56,
‘MUNICH’,
‘Programmer’)

Since this is your first application, lets make it simple.
We need to fetch the first_name and last_name from the employee table and show it on a PDF report named EmployeeReport.pdf

So the query for fetching the records to be displayed on the report is

select First_Name, Last_Name from employee e

Where to we need to provide this query?
Either we can provide it in the .jrxml file we created or in our invoking method(java class)

In this tutorial, we are talking about the case where we mention the query in the .jrxml file itself

EmployeeReport.jrxml

<?xml version=”1.0″ encoding=”UTF-8″?>
<!DOCTYPE jasperReport PUBLIC “//JasperReports//DTD Report Design//EN”
http://jasperreports.sourceforge.net/dtds/jasperreport.dtd”&gt;
<jasperReport name=”EmployeeReport_SuhasJavaBlog”>
<queryString>
<![CDATA[select First_Name, Last_Name from employee e]]>
</queryString>
<field name=”First_Name” />
<field name=”Last_Name” />
<title>
<band height=”50″>
<staticText>
<reportElement x=”0″ y=”0″ width=”180″ height=”15″/>
<textElement/>
<text><![CDATA[Jasper Report – SuhasJavaBlog]]></text>
</staticText>
</band>
</title>
<pageHeader>
<band height=”30″>
<staticText>
<reportElement x=”0″ y=”0″ width=”69″ height=”24″ />
<textElement verticalAlignment=”Bottom” />
<text>
<![CDATA[First Name: ]]>
</text>
</staticText>
<staticText>
<reportElement x=”140″ y=”0″ width=”79″ height=”24″ />
<text>
<![CDATA[Last Name: ]]>
</text>
</staticText>
</band>
</pageHeader>
<detail>
<band height=”30″>
<textField>
<reportElement x=”0″ y=”0″ width=”69″ height=”24″ />
<textFieldExpression>
<![CDATA[$F{First_Name}]]>
</textFieldExpression>
</textField>
<textField>
<reportElement x=”140″ y=”0″ width=”69″ height=”24″ />
<textFieldExpression>
<![CDATA[$F{Last_Name}]]>
</textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>

Note the highlighted text in the above template. (Thats our SQL query to fetch the records)

Now let’s take a look the Java code for generating the report. (We use Jasper API for this)

1. Establish a connection to the MySQL database :

Class.forName(“com.mysql.jdbc.Driver”);
conn = DriverManager.getConnection(“jdbc:mysql://localhost:3306/test?user=root&password=root”);

2. Read the .jrxml report template you have designed and create a JasperDesign Object which represent the report design :

InputStream input = new FileInputStream(new File(“jrxml/BasicReport.jrxml”));
JasperDesign jasperDesign = JRXmlLoader.load(input);

3. Now compile the report design file to create a JasperReport object. The compilation of the report design file validates the JasperReports XML file (EmployeeReport.jrxml) with the jaspereports.dtd DTD and converts the report expressions into a ready-to-evaluate form :

JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

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

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, conn);

In this example,  we don’t have any parameters to pass.

Hence we re-write this as

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, conn);

5. 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(“jrxml/EmployeeReport.pdf”));
JasperExportManager.exportReportToPdfStream(jasperPrint, output);

That’s it. You have done it. You just need to execute this method and you have your report ready under the ‘reports’ folder in your project

ReportGenerator.java

package de.suhas.jasper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

public class ReportGenerator {

Connection conn;

public void generateReport() {

try {
Class.forName(“com.mysql.jdbc.Driver”);
conn = DriverManager.getConnection(“jdbc:mysql://localhost:3306/test?user=root&password=root”);
System.out.println(“Loading Report Designs”);
InputStream input = new FileInputStream(new File(“jrxml/BasicReport.jrxml”));
JasperDesign jasperDesign = JRXmlLoader.load(input);

System.out.println(“Compiling Report Designs”);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

System.out.println(“Creating JasperPrint Object”);
Map<String, String> parameters = new HashMap<String, String>();
parameters.put(“ReportTitle”, “PDF JasperReport”);

System.out.println(“Filling Report to File”);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, conn);

//Exporting the report
OutputStream output = new FileOutputStream(new File(“jrxml/catalog.pdf”));
JasperExportManager.exportReportToPdfStream(jasperPrint, output);

System.out.println(“Report Generation Complete”);
conn.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JRException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
new ReportGenerator().generateReport();
}
}

Hope you guys have understood the art of creating reports using Jasper API and iReports.

Would love to hear from you guys if this was the slightest help to you.
Also feel free to drop in a reply for any queries related to Jasper Reports

Advertisements