jasper report

the own official web site provides the best documentation.

Compiling Report Designs
(back to top)
A report design is represented by a JRXML file that has the structure defined in the jasperreport.xsd file, or by an in-memory JasperDesign object. In order to generate reports according to such a report design, this needs to be compiled. Report design compilation can be done using the compileReportXXX() methods exposed by the JasperCompileManager class and results into a *.jasper file or a JasperReport object.
When compiling a report design, the engine first performs a validation to ensure that the template (JasperDesign) is consistent and then transforms all the report expressions in a ready-to-evaluate form, storing them inside the resulting compiled report template (JasperReport or .jasper file).
This transformation implies either the on-the-fly compilation of a Java class file that will be associated with the report template, or the generation of a Groovy or BeanShell script to use when evaluating report expressions during the report filling process, depending on the specified report expression language for the report (see the language property of a report template).

Before reading more about report compilation, you should understand when do you need to compile your report templates and which is the best way to do it by reading the following FAQ:
When should I compile my report templates and how?.

To make report design compilation process as flexible as possible, a special interface called JRCompiler was introduced.
As seen above, there are several different types of classes implementing this interface shipped with the library:
1. Java creport compilers. These report compilers generate and compile a Java class containing the report expressions evaluating methods; \\
2. The Groovy report compiler that generates a script for runtime report expressions evaluation.
3. The BeanShell report compiler that generates a script for runtime report expressions evaluation.

For more details about report compilation, check The Ultimate Guide to JasperReports.

Ant task for compiling report designs

Since the report design compilation process is more like a design-time job than a runtime one, an Ant task was provided with the library in order to simplify development.
This Ant task is implemented by the JRAntCompileTask and is very similar to the Ant built-in task, as far as syntax and behavior are concerned.
The report design compilation task can be declared like this, in a project’s build.xml file:

In the example above, the lib folder should contain the jasperreports-.jar file along with its required libraries (including the jdt-compiler-.jar, which is the recommended report compiler, in case you use Java as the report expression language).
This user-defined Ant task can be then used to compile multiple JRXML report design files in a single operation, by specifying the root directory that contains those files or by selecting them using file patterns. Attributes of the report design compilation task:
Attribute Description
srcdir Location of the JRXML report design files to compile. Required unless nested elements are present.
destdir Location to store the compiled report design files (the same as the source directory by default).
compiler Name of the class that implements the JRCompiler interface (optional).
xmlvalidation Flag to indicate if the XML validation should be performed on the source report design files (true by default).
tempdir Location to store the temporary generated files (the current working directory by default).
keepjava Flag to indicate if the temporary Java files generated on-the-fly should be kept and not deleted automatically (false by default).

The report design compilation task supports nested and elements, just like the Ant built-in task.

To see this in action, check the demo/samples/antcompile sample provided with the project source files.

Viewing a report design

Report designs can be viewed using the JasperDesignViewer application.
In its main() method, it receives the name of the file which contains the report design to view.
This can be the JRXML file itself, or the compiled report design (*.jasper file).

Filling Reports
(back to top)
A compiled report design can be used to generate reports by calling the fillReportXXX() methods of the JasperFillManager class. There are two flavours of the fill methods in this fa?ade class. Some receive a java.sql.Connection object as the third parameter, and the others receive a JRDataSource object instead.

This is because most of the times reports are filled with data from a relational database to which we connect through JDBC and is very convenient to have the SQL query inside the report template itself. The JasperReports engine can use the connection passed in and execute the SQL query, thus producing a report data source for filling the report.
In cases where data is available in other forms, the fill methods receiving a data source are to be used.

View, Print and Export Reports
(back to top)
Generated reports can be viewed using the JasperViewer application. In its main() method, it receives the name of the file which contains the report to view.

Generated reports can be printed using the printReport(), printPage() or printPages() static methods exposed by the JasperPrintManager class.

After having filled a report, we can also export it in PDF, HTML or XML format using the exportReportXXX() methods of the JasperExportManager class.

Parameters
(back to top)
Parameters are object references that are passed-in to the report filling operations. They are very useful for passing to the report engine data that it can not normally find in its data source. For example, we could pass to the report engine the name of the user that has launched the report filling operation if we want it to appear on the report, or we could dynamically change the title of our report.

An important aspect is the use of report parameters in the query string of the report, in order to be able to further customize the data set retrieved from the database. Those parameters could act like dynamic filters in the query that supplies data for the report.
Declaring a parameter in a report design is very simple and it requires specifying only its name and its class:

<parameter name=”ReportTitle” class=”java.lang.String”/>
<parameter name=”MaxOrderID” class=”java.lang.Integer”/>
<parameter name=”SummaryImage” class=”java.awt.Image”/>

There are two possible ways to use parameters in the query:

1. The parameters are used like normal java.sql.PreparedStatement parameters using the following syntax:

SELECT * FROM Orders WHERE CustomerID = $P{OrderCustomer}

2. Sometimes is useful to use parameters to dynamically modify portions of the SQL query or to pass the entire SQL query as a parameter to the report filling routines. In such a case, the syntax differs a little, like in the following example:

SELECT * FROM Orders ORDER BY $P!{OrderByClause}

There are also the following built-in system parameters, ready to use in expressions:

Data Source
(back to top)
JasperReports support various types of data sources using a special interface called JRDataSource.
There is a default implementation of this interface, the JRResultSetDataSource class, which wraps a java.sql.ResultSet object. It allows the use of any relational database through JDBC.
When using a JDBC data source, you could pass a java.sql.Connection object to the report filling operations and specify the query in the report definition itself (see the <queryString> element in the XML file) or could create a new instance of the JRResultSetDataSource by supplying the java.sql.ResultSet object directly.
With other types of data sources, things should not be different and all you have to do is to implement the JRDataSource interface, or use one of the implemetations that are shipped with the JasperReports library to wrap in-memory collections or arrays of JavaBeans, CSV or XML files, etc.

Fields
(back to top)
Report fields represent the only way to map data from the data source into the report generating routines. When the data source of the report is a java.sql.ResultSet, all fields must map to corresponding columns in the java.sql.ResultSet object. That is, they must have the same name as the columns they map and a compatible type.
For example:
If we want to generate a report using data retrieved from the table Employees, which has the following structure:
Column Name Datatype Length
EmployeeID int 4
LastName varchar 20
FirstName varchar 10
HireDate datetime 8
We can define the following fields in our report design:

<field name=”EmployeeID” class=”java.lang.Integer”/>
<field name=”LastName” class=”java.lang.String”/>
<field name=”FirstName” class=”java.lang.String”/>
<field name=”HireDate” class=”java.util.Date”/>

If we declare a field that does not have a corresponding column in the java.sql.ResultSet, an exception will be thrown at runtime. Columns present in the java.sql.ResultSet object that do not have corresponding fields in the report design do not affect the report filling operations, but they also won’t be accessible.

Expressions
(back to top)
Expressions are a powerful feature of JasperReports. They can be used for declaring report variables that perform various calculations, for data grouping on the report, to specify report text fields content or to further customize the appearance of objects on the report.
Basically, all report expressions are Java expressions that can reference report fields and report variables.
In an XML report design there are several elements that define expressions: <variableExpression>, <initialValueExpression>, <groupExpression>, <printWhenExpression>, <imageExpression> and <textFieldExpression>.
In order to use a report field reference in an expression, the name of the field must be put between $F{ and } character sequences.
For example, if we want to display in a text field, on the report, the concatenated values of two fields, we can define an expression like this one:

<textFieldExpression>
$F{FirstName} + ” ” + $F{LastName}
</textFieldExpression>

The expression can be even more complex:

<textFieldExpression>
$F{FirstName} + ” ” + $F{LastName} + ” was hired on ” +
(new SimpleDateFormat(“MM/dd/yyyy”)).format($F{HireDate}) + “.”
</textFieldExpression>

To reference a variable in an expression, we must put the name of the variable between $V{ and } like in the example below:

<textFieldExpression>
“Total quantity : ” + $V{QuantitySum} + ” kg.”
</textFieldExpression>

There is an equivalent syntax for using parameters in expressions. The name of the parameter should be put between $P{ and } like in the following example:

<textFieldExpression>
“Max Order ID is : ” + $P{MaxOrderID}
</textFieldExpression>

Variables
(back to top)
A Report variable is a special objects build on top of an expression. Variables can be used to simplify the report design by declaring only once an expression that is heavily used throughout the report design or to perform various calculations on the corresponding expressions.
In its expression, a variable can reference other report variables, but only if those referenced variables were previously defined in the report design. So the order in which the variables are declared in a report design is important.
As mentioned, variables can perform built-in types of calculations on their corresponding expression values like : count, sum, average, lowest, highest, variance, etc.
A variable that performs the sum of the Quantity field should be declared like this:

<variable name=”QuantitySum”
class=”java.lang.Double” calculation=”Sum”>
<variableExpression>$F{Quantity}</variableExpression>
</variable>

For variables that perform calculation we can specify the level at which they are reinitialized. The default level is Report and it means that the variable is initialized only once at the beginning of the report and that it performs the specified calculation until the end of the report is reached. But we can choose a lower level of reset for our variables in order to perform calculation at page, column or group level.
For example, if we want to calculate the total quantity on each page, we should declare our variable like this:

<variable name=”QuantitySum” class=”java.lang.Double”
resetType=”Page” calculation=”Sum”>
<variableExpression>$F{Quantity}</variableExpression>
<initialValueExpression>new Double(0) </initialValueExpression>
</variable>

Our variable will be initialized with zero at the beginning of each new page.
There are also the following built-in system variables, ready to use in expressions:

PAGE_NUMBER
COLUMN_NUMBER
REPORT_COUNT
PAGE_COUNT
COLUMN_COUNT
GroupName_COUNT

Documentation pending…

Report Sections
(back to top)
When building a report design we need to define the content and the layout of its sections. The entire structure of the report design is based on the following sections:

<background>
<title>
<pageHeader>
<columnHeader>
<groupHeader>
<detail>
<groupFooter>
<columnFooter>
<pageFooter>
<lastPageFooter>
<summary>
<noData>

Sections are portions of the report that have a specified height and width and can contain report objects like lines, rectangles, images or text fields.
When declaring the content and layout of a report section in an XML report design we use the generic element <band>.
This is how a page header declaration should look. It contains only a line object and a static text:

<pageHeader>
<band height=”30″>
<rectangle>
<reportElement x=”0″ y=”0″ width=”555″ height=”25″/>
<graphicElement/>
</rectangle>
<staticText>
<reportElement x=”0″ y=”0″ width=”555″ height=”25″/>
<textElement textAlignment=”Center”>
<font fontName=”Helvetica” size=”18″/>
</textElement>
<text>Northwind Order List</text>
</staticText>
</band>
</pageHeader>

Subreports
(back to top)
Subreports are an important feature for a report-generating tool. They allow the creation of more complex reports and simplify the design work.
Subreports are very useful when creating master-detail type of reports, or when the structure of a single report is not sufficient to describe the complexity of the desired output document.
A subreport is in fact a normal report incorporated into another report. One can overlap subreports or create subreports containing subreports themselves, up to any nesting level. Any report template can be used as a subreport when incorporated into another report, without anything inside it having to change.
Like other report elements, the subreport element has an expression that is evaluated at runtime in order to obtain the source of the JasperReport object to load.
There are two ways to supply parameter values to a subreport. First, you can use the <parametersMapExpression> element which introducest the expression that will be evaluated to produce the specified parameters map. And/or you can supply the parameters individually using a <subreportParameter> element for each relevant parameter. When using simultaneously both ways to supply parameters the parameters values specified using <subreportParameter> will override values specified with <parametersMapExpression>.
Subreports require a data source in order to generate their content, just like normal reports, behave in the same way, and expect to receive the same kind of input when they are being filled.
Values calculated by a subreport can be returned to the parent report. More specifically, after a subreport is filled, values of the subreport variables can be either copied or accumulated (using an incrementer) to variables of the caller report (master variables).
See the Subreport sample for details.

from : http://jasperforge.org/uploads/publish/jasperreportswebsite/trunk/tutorial.html

jasper report–example talks louder

Introduction

I’ve recently been researching reporting tools for a project I will be soon be working on. One of the tools I’ve been looking at is JasperReports. JasperReports is a very popular open source (LGPL) reporting library written in Java. Unfortunately it is not very well documented and I had a hard time coming up with a simple report. After some research, I was able to generate a simple report, this article summarizes what needs to be done to get started with JasperReports. See Resources for information on how to find additional information and documentation about JasperReports.
Getting Started

JasperReports’ reports are defined in XML files, which by convention have an extension of jrxml. A typical jrxml file contains the following elements:

<jasperReport> – the root element.
<title> – its contents are printed only once at the beginning of the report
<pageHeader> – its contents are printed at the beginning of every page in the report.
<detail> – contains the body of the report.
<pageFooter> – its contents are printed at the bottom of every page in the report.
<band> – defines a report section, all of the above elements contain a band element as its only child element.

All of the elements are optional, except for the root jasperReport element. Here is an example jrxml file that will generate a simple report displaying the string “Hello World!”
<?xml version=”1.0″?>
<!DOCTYPE jasperReport
PUBLIC “-//JasperReports//DTD Report Design//EN”
http://jasperreports.sourceforge.net/dtds/jasperreport.dtd”&gt;

<jasperReport name=”Simple_Report”>
<detail>
<band height=”20″>
<staticText>
<reportElement x=”180″ y=”0″ width=”200″ height=”20″/>
<text><![CDATA[Hello World!]]></text>
</staticText>
</band>
</detail>
</jasperReport>

For this simple example, I omitted the optional <title>, <pageHeader> and <pageFooter> elements. The <staticText> element, unsurprisingly, displays static text on the report, as can be seen, it contains a single <text> element defining the text that will be displayed.

jrxml files need to be “compiled” into a binary format that is specific to JasperReports, this can be achieved by calling the compileReport() method on the net.sf.jasperreports.engine.JasperCompileManager class. There are several overloaded versions of this method, in our example, we will use the one that takes a single String parameter, consult the JasperReport documentation for details on the other versions of the method.

public class JasperReportsIntro
{
public static void main(String[] args)
{
JasperReport jasperReport;
JasperPrint jasperPrint;
try
{
jasperReport = JasperCompileManager.compileReport(
“reports/jasperreports_demo.jrxml”);
jasperPrint = JasperFillManager.fillReport(
jasperReport, new HashMap(), new JREmptyDataSource());
JasperExportManager.exportReportToPdfFile(
jasperPrint, “reports/simple_report.pdf”);
}
catch (JRException e)
{
e.printStackTrace();
}
}
}

A jrxml file needs to be compiled only once, but for this simple example it is compiled every time the application is executed. Before a report can be generated, it needs to be “filled” with data, this is achieved by calling the fillReport() method on the net.sf.jasperreports.engine.JasperFillManager class. Again, there are several overloaded versions of the fillReport() method, here we will use one that takes three parameters, an instance of net.sf.jasperreports.engine.JasperReport, a java.util.HashMap containing any parameters passed to the report, and an instance of a class implementing the net.sf.jasperreports.engine.JRDataSource interface. The line that accomplishes this in our example above is

jasperPrint = JasperFillManager.fillReport(
jasperReport, new HashMap(), new JREmptyDataSource());

Since our simple report takes no parameters, we pass an empty HashMap as the second parameter, and an instance of net.sf.jasperreports.engine.JREmptyDataSource as the third parameter. JREmptyDataSource is a convenience class included with JasperReports, it is basically a DataSource with no data.

Finally, in our example, we export the report to a PDF file, this way it can be read by Adobe Acrobat, XPDF, Evince, or any other PDF reader, the line that accomplishes this in our example is

JasperExportManager.exportReportToPdfFile(
jasperPrint, “reports/simple_report.pdf”);

The parameters are self-explanatory.
Conclusion
JasperReports is a very good and popular open source reporting engine, this guide provides enough information to get started with JasperReports. For additional documentation, please see my book JasperReports For Java Developers .