Friday, June 22, 2012

Jasper Report for beginners


Jasper Reports is an open source reporting library which is available for windows and linux platforms. The Jasper report support many output formats like Excel, CVS, XML, PDF, HTML , RTF, Text etc..
It also supports many data sources like JDBC, Hibernate, EJB, Java Bean etc.,
The Jasper Report can be used on the web and also it can be used from simple Java application. It vastly supports the presentation formats like Dashboards, tables, cross tabs, and charts. Basically open and standards based Java and Xml. Supported by the most active community of report designers and developers.
The Jasper report simplifies the solution by providing support for multiple data sources, sub reports and cross tab reports. The built in virtualization capability of Jasper enables efficiently rendering large reports with limited available disk storage resources.
Report Life Cycle
• Jrxml file contain the report structure information.
• Jrxml file is converted into JasperDesign object by JRXmlLoader.
• JasperCompileManager parses the jrxml file and compiles it to JasperReport file. This file does not contain any data.
• JasperFillManager fills the data which is passed from various data sources.
• Using JRXlsExporter the excel file is generated.
Templates
Jasper uses jrxml templates to build and render the report. The jrxml is a standards based xml which can be dynamically generated using the open source tool iReport. iReport is the tool which can be used to generate the jrxml templates which can be connected to various data sources like JDBC, XML, Hibernate etc., Jrxml file contain the report structure information.
Report Basics
There are some basic steps involved in creating a Jasper Report. We will discuss a report generation steps for Excel output.
• Designing the Jasper Template.
• Compile Jasper Report.
• Fill Jasper Report using a data source.
• Export the Report.
We will discuss how each of the above operations can be done using a simple report. Our report uses Java Bean as the data source and generates multiple sheet Excel Report.
Designing the Jasper Template
Designing of Jasper Report involves generation of the Report Template, which is an Xml file with ‘jrxml’ extension. This template is a unique xml file which can be designed using an open source tool called iReport. It is very simple to design using the iReport tool. But once we understand the format, tags and attributes, it is very easy to edit manually.
Let us briefly discuss about the design of a simple template using iReport tool. iReport provides options to include Title, Page Header, Column Header, Detail, Column Footer etc., as per our requirement. Also there are options like Page Number, Total Pages, Page x of y, Sum, Current Date and percentage which can be inserted where ever needed. In our report template we just have the Column Header and details.
If you scrutiny the sample jrxml file given below, you will find the <jasperReport> tag with attributes like name, column count, page width, margins etc., which are specific to a report. Title and Page Header tags specify Title and Page Header information.
Column Headers are defined using an element called ‘Static Text’. For each Static Text element the cell level properties are defined using the tag ‘Report Element’. The cell type like Transparent or Opaque can be assigned using the attribute ‘mode’ of the ‘reportElement’ tag. Attributes x, y, width and height are so important for positioning and size of the cell. If you make a small mistake in any of the value, the entire report structure will be misaligned. You can specify a background color using ‘backcolor’ attribute but if you want to specify a background color, you must have the mode as Opaque.
It is not necessary to know the tags and attributes of the jrxml file, but if you know them basics it will be easy to fine tune the report and you will be able to identify the problem in case of any issues.
So far we have completed how the Header row is built in jrxml template. Now we will have a look at how the detail rows are built.
We will be using the ‘detail’ tag to display the detail rows. We use ‘textField’ tag and ‘textFieldExpression’ tag is used in which the field name is passed. For example ‘personName’ is the field we are using. Firstly you need to create a field by that name specifying the type of the field.
<field name=”personName” class=”java.lang.String”/>
Later in the ‘textFieldExpression’ tag you need to specify the field name as shown below.
<textFieldExpression class=”java.lang.String”><![CDATA[$F{personName}]]></textFieldExpression>

Go through the jrxml file details given below and try to understand the structure and usage of various tags and attributes. A faster way to learn is by experimenting it using iReport. When ever you change some thing using iReport, the jrxml file is getting modified.
Simple jrxml file.
<?xml version=”1.0″ encoding=”UTF-8″ ?>
<!– Created with iReport – A designer for JasperReports –>
<!DOCTYPE jasperReport PUBLIC “//JasperReports//DTD Report Design//EN” “http://jasperreports.sourceforge.net/dtds/jasperreport.dtd”>
<jasperReport
name=”FirstReport”
columnCount=”1″
printOrder=”Vertical”
orientation=”Portrait”
pageWidth=”595″
pageHeight=”842″
columnWidth=”555″
columnSpacing=”0″
leftMargin=”20″
rightMargin=”20″
topMargin=”30″
bottomMargin=”30″
whenNoDataType=”NoPages”
isTitleNewPage=”false”
isSummaryNewPage=”false”>
<property name=”ireport.scriptlethandling” value=”0″ />
<property name=”ireport.encoding” value=”UTF-8″ />
<import value=”java.util.*” />
<import value=”net.sf.jasperreports.engine.*” />
<import value=”net.sf.jasperreports.engine.data.*” /><field name=”personName” class=”java.lang.String”/>
<field name=”country” class=”java.lang.String”/>
<field name=”state” class=”java.lang.String”/>
<field name=”city” class=”java.lang.String”/><background>
<band height=”0″ isSplitAllowed=”true” >
</band>
</background>
<title>
<band height=”0″ isSplitAllowed=”true” >
</band>
</title>
<pageHeader>
<band height=”0″ isSplitAllowed=”true” >
</band>
</pageHeader>
<columnHeader>
<band height=”23″ isSplitAllowed=”false” >
<staticText>
<reportElement
mode=”Opaque”
x=”0″
y=”0″
width=”200″
height=”20″
backcolor=”#CCCCCC”
key=”staticText”/>
<box> <pen lineWidth=”0.5″/>
<topPen lineWidth=”0.5″/>
<leftPen lineWidth=”0.5″/>
<bottomPen lineWidth=”0.5″/>
<rightPen lineWidth=”0.5″/>
</box>
<textElement textAlignment=”Center” verticalAlignment=”Middle” rotation=”None” lineSpacing=”Single”>
<font fontName=”Arial” size=”10″ isBold=”true” isItalic=”false” isUnderline=”false” isStrikeThrough=”false” />
</textElement>
<text><![CDATA[Name]]></text>
</staticText>
<staticText>
<reportElement
mode=”Opaque”
x=”200″
y=”0″
width=”100″
height=”20″
backcolor=”#CCCCCC”
key=”staticText”/>
<box> <pen lineWidth=”0.5″/>
<topPen lineWidth=”0.5″/>
<leftPen lineWidth=”0.5″/>
<bottomPen lineWidth=”0.5″/>
<rightPen lineWidth=”0.5″/>
</box>
<textElement textAlignment=”Center” verticalAlignment=”Middle” rotation=”None” lineSpacing=”Single”>
<font fontName=”Arial” size=”10″ isBold=”true” isItalic=”false” isUnderline=”false” isStrikeThrough=”false” />
</textElement>
<text><![CDATA[Country]]></text>
</staticText>
<staticText>
<reportElement
mode=”Opaque”
x=”300″
y=”0″
width=”100″
height=”20″
backcolor=”#CCCCCC”
key=”staticText”/>
<box> <pen lineWidth=”0.5″/>
<topPen lineWidth=”0.5″/>
<leftPen lineWidth=”0.5″/>
<bottomPen lineWidth=”0.5″/>
<rightPen lineWidth=”0.5″/>
</box>
<textElement textAlignment=”Center” verticalAlignment=”Middle” rotation=”None” lineSpacing=”Single”>
<font fontName=”Arial” size=”10″ isBold=”true” isItalic=”false” isUnderline=”false” isStrikeThrough=”false” />
</textElement>
<text><![CDATA[State]]></text>
</staticText>
<staticText>
<reportElement
mode=”Opaque”
x=”400″
y=”0″
width=”100″
height=”20″
backcolor=”#CCCCCC”
key=”staticText”/>
<box> <pen lineWidth=”0.5″/>
<topPen lineWidth=”0.5″/>
<leftPen lineWidth=”0.5″/>
<bottomPen lineWidth=”0.5″/>
<rightPen lineWidth=”0.5″/>
</box>
<textElement textAlignment=”Center” verticalAlignment=”Middle” rotation=”None” lineSpacing=”Single”>
<font fontName=”Arial” size=”10″ isBold=”true” isItalic=”false” isUnderline=”false” isStrikeThrough=”false” />
</textElement>
<text><![CDATA[City]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height=”24″ isSplitAllowed=”false” >
<textField isStretchWithOverflow=”true” pattern=”" isBlankWhenNull=”true” evaluationTime=”Now” hyperlinkType=”None” hyperlinkTarget=”Self” >
<reportElement
x=”0″
y=”0″
width=”200″
height=”18″
key=”textField”/>
<box> <pen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<topPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<leftPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<bottomPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<rightPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
</box>
<textElement>
<font/>
</textElement>
<textFieldExpression class=”java.lang.String”><![CDATA[$F{personName}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow=”false” isBlankWhenNull=”false” evaluationTime=”Now” hyperlinkType=”None” hyperlinkTarget=”Self” >
<reportElement
x=”200″
y=”0″
width=”100″
height=”18″
key=”textField”/>
<box> <pen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<topPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<leftPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<bottomPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<rightPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
</box>
<textElement>
<font/>
</textElement>
<textFieldExpression class=”java.lang.String”><![CDATA[$F{country}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow=”true” isBlankWhenNull=”false” evaluationTime=”Now” hyperlinkType=”None” hyperlinkTarget=”Self” >
<reportElement
x=”300″
y=”0″
width=”100″
height=”18″
key=”textField”/>
<box> <pen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<topPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<leftPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<bottomPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<rightPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
</box>
<textElement>
<font/>
</textElement>
<textFieldExpression class=”java.lang.String”><![CDATA[$F{state}]]></textFieldExpression>
</textField>
<textField isStretchWithOverflow=”true” isBlankWhenNull=”false” evaluationTime=”Now” hyperlinkType=”None” hyperlinkTarget=”Self” >
<reportElement
x=”400″
y=”0″
width=”100″
height=”18″
key=”textField-1″/>
<box> <pen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<topPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<leftPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<bottomPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
<rightPen lineWidth=”0.5″ lineStyle=”Solid” lineColor=”#CCCCCC”/>
</box>
<textElement>
<font/>
</textElement>
<textFieldExpression class=”java.lang.String”><![CDATA[$F{city}]]></textFieldExpression>
</textField>
</band>
</detail>
<columnFooter>
<band height=”0″ isSplitAllowed=”true” >
</band>
</columnFooter>
<pageFooter>
<band height=”0″ isSplitAllowed=”true” >
</band>
</pageFooter>
<summary>
<band height=”0″ isSplitAllowed=”true” >
</band>
</summary>
</jasperReport>

Compile Jasper Report
import java.util.HashMap;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
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;public class CompileReport {
public static void main(String[] args) {
//JasperReport jasperReport;
JasperPrint jasperPrint;
try {
JasperCompileManager.compileReportToFile(“C:\\eclipse\\workspace\\NewJasper\\src\\FirstJasper.jrxml”);
JasperCompileManager.compileReportToFile(“C:\\eclipse\\workspace\\NewJasper\\src\\SecondJasper.jrxml”);}
catch (JRException e) {
e.printStackTrace();
}
}
}
In the above example we have two jrxml templates, one for each sheet in our excel report. We assume that we have completed the design of both of our jrxml templates. The next step is to compile them.

JasperCompileManager.compileReportToFile(“C:\\eclipse\\workspace\\NewJasper\\src\\FirstJasper.jrxml”);
Just call the method compileReportToFile of JasperCompileManager by passing the jrxml file name (FirstJasper.jrxml). The report gets compiled and a new FirstJasper.jasper file is generated.
Fill Jasper Report using a data source
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRPrintPage;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;public class ExportDemoExcel {
public static void main(String args[]){
try {
Object[] objArr = new Object[3];
objArr[0]= new DemoBean(“Ramesh”,”USA”,”CA”, “San Jose”, “Jasper Report”, 2, “San Jose”, “Expert”);
objArr[1]= new DemoBean(“Suresh”,”USA”,”CA”, “San Jose”, “Jasper Report”, 2, “San Jose”, “Expert”);
objArr[2]= new DemoBean(“Paul”,”USA”,”CA”, “San Jose”, “Jasper Report”, 2, “San Jose”, “Expert”);
JasperPrint jp1 = JasperFillManager.fillReport(“C:\\eclipse\\workspace\\NewJasper\\src\\FirstReport.jasper”, new HashMap(), new JRBeanArrayDataSource(objArr));
JasperPrint jp2 = JasperFillManager.fillReport(“C:\\eclipse\\workspace\\NewJasper\\src\\SecondReport.jasper”, new HashMap(), new JRBeanArrayDataSource(objArr));
List<JRPrintPage> pages = new ArrayList<JRPrintPage>(jp2.getPages());
int i=1;
for(int count=0;count<pages.size();count++){
jp1.addPage(i, (JRPrintPage)pages.get(count));
i++;
}JRXlsExporter exporter = new JRXlsExporter();
exporter.setParameter(JRXlsExporterParameter.
IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
Boolean.TRUE);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jp1);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
“e:/demo1.xls”);
exporter.setParameter(JRXlsExporterParameter.SHEET_NAMES, new String[]{”Personal Information”, “Skills”});
exporter.setParameter(JRXlsExporterParameter.IGNORE_PAGE_MARGINS,
Boolean.TRUE);
exporter.setParameter(JRXlsExporterParameter.OFFSET_X, 0);
exporter.setParameter(JRXlsExporterParameter.IS_IGNORE_CELL_BORDER, Boolean.FALSE);
exporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, true);
exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, false);
exporter.exportReport();

} catch (JRException e) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace();
}
}
}
We are using the Java Bean as the data source. The next operation will be filling the report.
JasperPrint jp1 = JasperFillManager.fillReport(“C:\\eclipse\\workspace\\NewJasper\\src\\FirstReport.jasper”, new HashMap(), new JRBeanArrayDataSource(obj));
Just call the ‘fillReport’ method of the ‘JasperFillManager’ class by passing the jasper file name and the data source. In our case the data source is an Object Array containing the Java Beans. Make a note that the field names which we use in the template should match the Java Bean attribute, otherwise it will through an error. When the fill operation is successful, file is generated with the jrpint extension. In our case it will be FirstReport.jrprint.
Adding multiple Sheets in our excel report
List<JRPrintPage> pages = new ArrayList<JRPrintPage>(jp2.getPages());
int i=1;
for(int count=0;count<pages.size();count++){
jp1.addPage(i, (JRPrintPage)pages.get(count));
i++;

In our case we use two jrxml files one for each sheet. There fore there two jrprint file are generated. In the above code we just adding the sheets to the report.
Export Excel
JRXlsExporter exporter = new JRXlsExporter();
exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET,
Boolean.FALSE);
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jp1);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
“e:/demo1.xls”);
//Pass the sheet names
exporter.setParameter(JRXlsExporterParameter.SHEET_NAMES, new String[]{”Personal Information”, “Skills”});
exporter.setParameter(JRXlsExporterParameter.IGNORE_PAGE_MARGINS,
Boolean.TRUE);
exporter.setParameter(JRXlsExporterParameter.OFFSET_X, 0);
exporter.setParameter(JRXlsExporterParameter.IS_IGNORE_CELL_BORDER, Boolean.FALSE);
exporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, true);
exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, false);
exporter.exportReport();

Before exporting a report we are passing some export parameters as shown above. This is because by default these parameters have some initial values and that may affect the appearance of our report. The report file is exported and stored in the specified path.

No comments:

Advance Java Blogging

Java New Articles

Javas Latest News

Java Web Services and XML

Ajax Latest News

Mac OS Java Features

Advance Spotlights

Patterns Features