Anda di halaman 1dari 18

JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.

jasperreports/wiki/Tutorial Page No 1 of 18

JasperReports Tutorial

1. Introduction
2. API Overview
3. Report Designs
4. Compiling Report Designs
5. Filling Reports
6. View, Print and Export Reports
7. Parameters
8. Data Source
9. Fields
10. Expressions
11. Variables
12. Report Sections
13. Frames
14. Groups
15. Fonts and Unicode Support
16. Styles
17. Scriptlets
18. Subreports
19. I18n
20. Datasets
21. Charts
22. Crosstabs

JasperReports Tutorial - Introduction


JasperReports is a powerful open source reporting tool that has the ability to deliver rich
content onto the screen, to the printer, or into PDF, HTML, XLS, CSV and XML files. It is
entirely written in Java and can be used in a variety of Java-enabled applications to generate
dynamic content. Its main purpose is to help create page-oriented, ready-to-print documents
in a simple and flexible manner.

JasperReports organizes data retrieved from a relational database through JDBC according to
a report-design defined in an XML file. In order to fill a report with data, the report-design
must be compiled first.

The compilation of the XML file representing the report-design is performed by the
compileReport() method exposed by the net.sf.jasperreports.engine.JasperManager class.
Through compilation, the report design is loaded into a report-design object that is then
serialized and stored on disk (net.sf.jasperreports.engine.JasperReport). This serialized object
is used when the application wants to fill the specified report-design with data. In fact, the
compilation of a report-design implies the compilation of all Java expressions defined in the
XML file representing the report design. Various verifications are made at compilation time,
to check the report-design consistency. The result is a ready-to-fill report-design that will be
used to generate documents on different sets of data.
JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.jasperreports/wiki/Tutorial Page No 2 of 18

In order to fill a report-design, one can use the fillReportXXX() methods exposed by the
net.sf.jasperreports.engine.JasperManager class. Those methods receive as a parameter the
report-design object, or a file representing the specified report-design object, in a serialized
form, and also a JDBC connection to the database from which to retrieve the data to fill the
report with. The result is an object that represents a ready-to-print document
(net.sf.jasperreports.engine.JasperPrint) and that can be stored on disk in a serialized form
(for later use), can be delivered to the printer or to the screen, or can be transformed into a
PDF, HTML, XLS, CSV or XML document.

Contents Next >>

JasperReports Tutorial - API Overview


Main classes to use when working with JasperReports

net.sf.jasperreports.engine.JasperCompileManager
net.sf.jasperreports.engine.JasperFillManager
net.sf.jasperreports.engine.JasperPrintManager
net.sf.jasperreports.engine.JasperExportManager
These classes represent a façade to the JasperReports engine. They have various static
methods that simplify the access to the API functionality and can be used to compile an XML
report design, to fill a report, to print it, or to export to PDF, HTML and XML files.

net.sf.jasperreports.view.JasperViewer
This can be used to view the generated reports.

net.sf.jasperreports.view.JasperDesignViewer
This can be used to view the report design.

JasperReports Tutorial - Report Designs


As mentioned, a report design represents a template that will be used by the JasperReports
engine to deliver dynamic content to the printer, to the screen or to the Web. Data stored in
the database is organized according to the report design to obtain ready to print, page oriented
documents.
The report designs are defined in XML files and must have a special structure. This structure
is declared in a DTD file supplied with the JasperReports engine. The XML files are then
compiled, in order to use them in report filling operations.
To create a simple report design, we have to edit an XML file with the following structure:

<?xml version="1.0"?>
<!DOCTYPE jasperReport
PUBLIC "-//JasperReports//DTD Report Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">

<jasperReport name="name_of_the_report" ... >


...
</jasperReport>
JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.jasperreports/wiki/Tutorial Page No 3 of 18

JasperReports Tutorial - Compiling Report Designs

A report design is represented by an XML file that has the structure defined in the
jasperreport.dtd file. In order to generate reports according to such a report design, it needs to
be compiled. Report design compilation can be done using the compileReportXXX() methods
exposed by net.sf.jasperreports.engine.JasperCompileManager class. When compiling a
report design, the engine first performs a validation to ensure that the template is consistent
and then transforms all the report expressions, so that they are stored in a ready-to-evaluate
form, inside the resulting .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 BeanShell script to use when evaluating report expressions during the report
filling process. To make report design compilation process as flexible as possible, a special
interface called net.sf.jasperreports.engine.design.JRCompiler was introduced. As seen
above, there are two main types of classes implementing this interface and thus performing
report compilation: 1. Java class generating report compilers. These report compilers generate
and compile a Java class containing the report expressions evaluating methods; 2. The
BeanShell report compiler that generates a script for runtime report expressions evaluation,
without requiring bytecode Java compilation. System properties to customize report
compilation: jasper.reports.compiler.class By default, when compiling report designs, the
library tries to identify the Java generating class type of a report compiler that is compatible
with the Java compiler available on the running platform in this order: JDK 1.3 compatible
compiler, JDK 1.2 compatible compiler and the command-line javac.exe compiler. To
override this default behavior, you can specify the name of a class that implements the
net.sf.jasperreports.engine.design.JRCompiler interface to be used to compile the report
design by supplying it to the jasper.reports.compiler.class system property. The library comes
with 5 built-in implementations of this interface:
net.sf.jasperreports.engine.design.JRJavacCompiler
net.sf.jasperreports.engine.design.JRJdk12Compiler
net.sf.jasperreports.engine.design.JRJdk13Compiler
net.sf.jasperreports.engine.design.JRJdtCompiler
net.sf.jasperreports.engine.design.JRJikesCompiler Note that the classes implementing the
JRCompiler interface can also be used directly in the programs without the need to call them
through the faæ ¤e JasperCompilerManager class. jasper.reports.compilation.xml.validation
The XML validation, which is ON by default, can be turned off by setting the system
property called jasper.reports.compilation.xml.validation to false. When working with a Java
JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.jasperreports/wiki/Tutorial Page No 4 of 18

class generating type of a report compiler, further customizations can be made using the
following system properties, which only apply to them: jasper.reports.compile.class.path By
default, JasperReports uses the current JVM classpath to compile the report class
(java.class.path system property). To customize this report compilation process,
JasperReports lets you override the default behavior by supplying a value to the
jasper.reports.compile.class.path system property, which will be used as classpath for the
report class compilation. jasper.reports.compile.temp The temporary location for the files
generated on-the-fly is by default the current working directory. It can be changed by
supplying a value to the jasper.reports.compile.temp system property.
jasper.reports.compile.keep.java.file Sometimes, for debugging purposes, it is useful to have
the generated .java file in order to fix the compilation problems related to report expressions.
By default, the engine deletes this file after report compilation, along with its
corresponding .class file. To keep it however, you can set the system property
jasper.reports.compile.keep.java.file to true.

Ant task for compiling report designs top 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
net.sf.jasperreports.ant.JRAntCompileTask and is very similar to the <javac> 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: <taskdef name="jrc"
classname="net.sf.jasperreports.ant.JRAntCompileTask"> <classpath> <fileset dir="./lib">
<include name="**/*.jar"/> </fileset> </classpath> </taskdef> In the example above, the lib
should contain the jasperreports.jar file along with its required libraries. This user-defined
Ant task can be then used to compile multiple XML 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: srcdir Location of the XML report
design files to compile. Required unless nested <src> 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
net.sf.jasperreports.engine.design.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
JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.jasperreports/wiki/Tutorial Page No 5 of 18

compilation task supports nested <src> and <classpath> elements, just like the Ant <javac>
built-in task. To see this in action, check the "antcompile" sample provided with the project
source files.
Viewing a report design top
Reports designs can be viewed using the net.sf.jasperreports.view.JasperDesignViewer
application. In its main() method, it receives the name of the file which contains the report
design to view. This can be the XML file itself, or the compiled report design.

JasperReports Tutorial - Filling Reports

A compiled report design can be used to generate reports by calling the fillReportXXX()
methods of the net.sf.jasperreports.engine.JasperFillManager class.

JasperReports Tutorial - View, Print and Export Reports


Viewing a report
Generated reports can be viewed using the net.sf.jasperreports.view.JasperViewer
application. In its main() method, it receives the name of the file which contains the report to
view.
Printing a report
Generated reports can be printed using the printReport(), printPage() or printPages() static
methods exposed by the net.sf.jasperreports.engine.JasperPrintManager class.
Exporting to PDF, HTML, XLS, CSV or XML format
After having filled a report, we can also export it in PDF, HTML or XML format using the
exportReportXXX() methods of the net.sf.jasperreports.engine.JasperExportManager class.

JasperReports Tutorial - Parameters

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 import 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.
JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.jasperreports/wiki/Tutorial Page No 6 of 18

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:
Parameter Name Description
This parameter will contain a map with all user defined
REPORT_PARAMETERS_MAP
and built-in parameters.
A user supplied java.sql.Connection used for JDBC
REPORT_CONNECTION
datasources.
A user supplied instance of JRDataSource representing
REPORT_DATA_SOURCE either one of the built-in data source types or a user-
defined one.
REPORT_MAX_COUNT An integer allowing users to limit the datasource size.
A JRAbstractScriptlet containing an instance of the report
REPORT_SCRIPTLET
scriptlet provided by the user.
A java.util.Locale instance containing the resource bundle
REPORT_LOCALE
desired locale.
The java.util.ResourceBundle containing localized
REPORT_RESOURCE_BUNDLE
messages.
REPORT_TIME_ZONE A java.util.TimeZone instance to use for date formatting.
The net.sf.jasperreports.engine.JRVirtualizer object to be
REPORT_VIRTUALIZER
used for page virtualization.
A java.lang.C~lassLoader instance to be used during the
REPORT_CLASS_LOADER report filling process to load resources such as images,
fonts and subreport templates.
If set to jaa.lang.Boolean.TRUE the report will be
IS_IGNORE_PAGINATION
generated on one long page and page break will not occur.

JasperReports Tutorial - Data Source


JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.jasperreports/wiki/Tutorial Page No 7 of 18

JasperReports support various types of data sources using a special interface called
JRDataSource.

There is a default implementation of this interface (JRResultSetDataSource class) that wraps


a ResultSet object. It allows the use of any RDMS database through JDBC.

When using a JDBC data source, one could pass a 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 ResultSet object directly.

With other types of data sources, things should not be different and all we have to do is to
implement the JRDataSource interface.

JasperReports Tutorial - Fields

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 ResultSet, all fields must map to
corresponding columns in the 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 ResultSet, an exception
will be thrown at runtime. Columns present in the ResultSet object that do not have
corresponding fields in the report design do not affect the report filling operations, but they
also wont be accessible.

JasperReports Tutorial - Expressions


JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.jasperreports/wiki/Tutorial Page No 8 of 18

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>

JasperReports Tutorial - Variables

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.
JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.jasperreports/wiki/Tutorial Page No 9 of 18

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...

JasperReports Tutorial - Report Sections

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>,
<columnFoter>, <pageFooter>, <lastPageFooter>, <summary>.

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/>
JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.jasperreports/wiki/Tutorial Page No 10 of 18

</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>

JasperReports Tutorial - Frames

Sometimes a group of elements have to share a common background or have a common


border around them. This was achieved by putting a rectangle behind them, but it did not
work with the grid exporters since overlapping elements are not supported there.

The new frame element is recognized by the grid exporters and can be used to group elements
together by nesting them inside a frame. Frames can be nested on an unlimited number of
levels.

JasperReports Tutorial - Groups

Groups represent a flexible way to organize data on a report. When filling a report, the
JasperReports engine tests all the defined group expressions to see whether a group rupture
has occurred and if so it introduces the corresponding <groupFooter> and <groupHeader>
sections on the report.

We can have as many groups as we want on a report. The order of groups declared in a report
design is important because groups contain each other. One group contains the following
group and so on. When a larger group encounters a rupture, all subsequent groups are
reinitialized.

When declaring a report group, along with its corresponding data grouping expression, we
have to declare the two sections: the group's header section and the group's footer section.

See the Jasper Sample report for an example on how to define groups.

JasperReports Samples

The JasperReports entire project tree, containing this documentation and the library source
files, comes also with several demo applications that are easy to run and test using the ANT
build tool.

The project is available for download at the JasperForge Developer Forge.


JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.jasperreports/wiki/Tutorial Page No 11 of 18

The samples can be found in the demo/samples directory of the project. Some of them use
data from the HSQL default database that is also supplied in the demo/hsqldb directory of the
project.

All the XML report designs are validated against a DTD file which is internal to the library
jasperreports.jar.

Details about the structure of an XML report design and the use of different elements are
available in the Quick Reference document.

Here is a copy of the actual DTD file: jasperreport.dtd

For a quick review of the JasperReports library features, we present here some of those
sample reports.

Barbecue Sample

Sample that shows how to include barcodes inside reports using the Barbecue open source
library.
BarbecueReport.jrxml >> BarbecueReport.pdf >> BarbecueReport.html

Crosstab Sample

Crosstabs are a special type of table component in which both the rows and the columns are
dynamic. They are used to display aggregated data using tables with multiple levels of
grouping for both columns and groups.
ShipmentsReport.jrxml >> ShipmentsReport.pdf >> ShipmentsReport.html

Data Source Sample

When generating reports, JasperReports can make use of various kinds of data, as long as the
parent application provides a custom implementation of the
net.sf.jasperreports.engine.JRDataSource interface that will allow it to retrieve that data. The
library comes with a default implementation of this interface that wraps a java.sql.ResultSet
object and lets people use JDBC data sources seamlessly.
DataSourceReport.jrxml >> DataSourceReport.pdf >> DataSourceReport.html

Fonts Sample

Text formatting features are very important in document generating software and
JasperReports offers a complete range of font settings: size, style, text alignment, color, etc.
FontsReport.jrxml >> FontsReport.pdf >> FontsReport.html

Horizontal Sample

The engine can fill multi-column reports either vertically (from top to bottom) or horizontally
(from left to right), depending on the "printOrder" attribute specified in the report design.
Here's a sample showing the detail section being generated horizontally.
HorizontalReport.jrxml >> HorizontalReport.pdf >> HorizontalReport.html

Hyperlink Sample
JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.jasperreports/wiki/Tutorial Page No 12 of 18

This sample illustrates the use of hyperlink elements. They allow the creation of drill-down
repots and generally speaking offer a higher degree of interaction with the document viewers.

HyperlinkReport.jrxml >> HyperlinkReport.pdf >> HyperlinkReport.html

I18n Sample

The library has built-in support for generating documents in different languages.
I18nReport.jrxml >> I18nReport.pdf >> I18nReport.html

Images Sample

In this sample, users will learn how to use image elements in their reports.
ImagesReport.jrxml >> ImagesReport.pdf >> ImagesReport.html

Jasper Sample
This is the most complex sample provided with the package. It explains how to use data
grouping and more complex element formatting.
FirstJasper.jrxml >> FirstJasper.pdf >> FirstJasper.html

JFreeChart Sample

This sample shows how you can include graphics and charts into your reports. The
JasperReports library does not produce graphics and charts itself, but allows the use of other
specialized libraries and easily integrates this type of elements into the documents it
generates.
JFreeChartReport.jrxml >> JFreeChartReport.pdf >> JFreeChartReport.html

Landscape Sample

Shows how to set up a report in "Landscape" format.


LandscapeReport.jrxml >> LandscapeReport.pdf >> LandscapeReport.html

Scriptlet Sample

Scriptlets are a very flexible feature of the JasperReports library and can be used in many
situations to manipulate the report data during the report filling process.
ScriptletReport.jrxml >> ScriptletReport.pdf >> ScriptletReport.html

Shapes Sample

Shows how different graphic elements such as lines and rectangles can be used in the
documents.
ShapesReport.jrxml >> ShapesReport.pdf >> ShapesReport.html

Stretch Sample

This is a special sample with debug purposes. It shows how the text fields behave when they
stretch downwards in order to acquire their entire content. Element stretching and page
overflow mechanisms are very sensitive aspects of report generating tools.
StretchReport.jrxml >> StretchReport.pdf >> StretchReport.html
JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.jasperreports/wiki/Tutorial Page No 13 of 18

Styled Text Sample

The text elements can contain style information introduced using an XML syntax based on
nested <styled> tags.
StyledTextReport.jrxml >> StyledTextReport.pdf >> StyledTextReport.html

Subreport Sample

Illustrates how subreports might be used in more complex reports.


MasterReport.jrxml >> MasterReport.pdf >> MasterReport.html

Table of Contents Sample

Some reports may require the creation of a "table of contents" structure, either at the
beginning of the document or at the end. Here is a simple example for those who want to
learn how to create such structures.
TableOfContentsReport.jrxml >> TableOfContentsReport.pdf >>
TableOfContentsReport.html

Unicode Sample

JasperReports can generate documents in any language. This is a simple example that shows
how font and text encoding settings should be used.
UnicodeReport.jrxml >> UnicodeReport.pdf >> UnicodeReport.html

JasperReports Tutorial - Fonts and Unicode Support

Now you can create your reports in any language!

New attributes in the <font> element where introduced to allow the mapping between the
Java fonts and the PDF fonts.

PDF uses special font settings and there was no way to make use of them in the previous
version of JasperReports.

With the introduction of those new attributes, the users can specify what PDF specific font
should be used to display different character sets (pdfFontName attribute), what is the type of
the encoding (pdfEncoding attribute) and whether the font should be embedded in the PDF
document or not (isPdfEmbedded).

To simplify the use of the font settings, a new element was introduced: <reportFont>.
Report fonts are report level font definitions that ca be used as default or base font settings in
other font definitions throughout the entire report.

Since the support for international characters is somehow tied to the iText library, you can
find more details about how to create PDF documents in different languages and different
character sets in the iText documentation.
JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.jasperreports/wiki/Tutorial Page No 14 of 18

JasperReports Tutorial - Styles

Report styles were introduced in order to group together a set of visual properties that would
then be applied to report elements that reference the report style. This new concept is an
extension of the former report font concept which is now deprecated. Report elements that
reference a report style definition could override the values of any visual property defined in
the style. Report styles could also reference other report styles and the same inheritance and
override mechanism applies to them too.

Styles are useful when a whole range of elements need to share the same visual properties
and any change made to that has to apply to all of them. This can be achieved by changing
the report style they all reference.

JasperReports Tutorial - Scriptlets

All the data displayed on a report comes from the report parameters and from the report
fields. This data can be processed using the report variables and their expressions.

There are specific moments in time when variable processing occurs. Some variables are
initialized according to their reset type when the report starts, or when a page or column
break is encountered, or when a group changes. Furthermore, variables are evaluated every
time new data is fetched from the data source (for every row).

But only simple variable expressions cannot always implement complex functionality. This is
where scriptlets intervene.

Scriptlets are sequences of Java code that are executed every time a report event occurs.
Through scriptlets, users now have the possibility to affect the values stored by the report
variables.

Since scriptlets work mainly with report variables, is important to have full control over the
exact moment the scriptlet is executed. JasperReports allows the execution of custom Java
code BEFORE or AFTER it initializes the report variables according to their reset type:
Report, Page, Column or Group.

In order to make use of this functionality, users only have to create a scriptlet class by
extending net.sf.jasperreports.engine.JRAbstractScriptlet class or
net.sf.jasperreports.engine.JRDefaultScriptlet class. The name of this custom scriptlet class
has to be specified in the scriptletClass attribute of the <jasperReport> element.

When creating a JasperReports scriptlet class, there are several methods that developers
should implement or override, like: beforeReportInit(), afterReportInit(), beforePageInit(),
afterPageInit(), beforeGroupInit(), afterGroupInit(), etc. Those methods will be called by the
report engine at the appropriate time, when filling the report.

There is a default report parameter called REPORT_SCRIPTLET which represent a reference


to the scriptlet object instantiated by the report engine when filling the report. It can be used
in expressions throughout the report, to call custom methods on the scriptlet object, making
the whole mechanism even more flexible.
JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.jasperreports/wiki/Tutorial Page No 15 of 18

And that is all!

See the ScriptletReport sample for more details.

JasperReports Tutorial - Subreports

Subreports are an import feature for a report-generating tool. They allow the creation of more
complex reports and simplify the design work.

The subreports are very useful when creating master-detail type of reports.

Documentation pending...
subreport example1

wiki1278: SubreportExample1 in this example i'v used the sub report feature to create a
report on a company, and a detailed subreport on it's contacts. the master report is called
companyD.jrxml, and the employees subreport is called companySubReport.jrxml (attached
below).

lets look at the master report, inside the details band, i'v added a subreport node that looks
like this:

<subreport isUsingCache="true">

<reportElement x="29" y="22" width="385" height="19" key="subreport-1"/>

<parametersMapExpression> <![CDATA[$P{REPORT_PARAMETERS_MAP}]]>
</parametersMapExpression>

<dataSourceExpression> <![CDATA[new JRBeanCollectionDataSource($F{contacts})]]>


</dataSourceExpression>

<subreportExpression class="java.io.InputStream"> <!


[CDATA[$P{REPORT_PARAMETERS_MAP}.get("SubreportStream")]]>
</subreportExpression>

</subreport>

the subreport element need 2 things to work properly:

1. the <subreportExpression> wich is the url (or in this case i'v used an InputStream that
i send in the REPORT_PARAMETERS_MAP, i'll explain how to do this later) of the
subreport, so that the jasper framework will be able to load the subreport design.
2. the <dataSourceExpression> expression wich tells the subreport from where to get his
data from.

there is also the <parametersMapExpression> element, but in most cases you just send the
mster REPORT_PARAMETERS_MAP.

the code to invoke the master report is :


JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.jasperreports/wiki/Tutorial Page No 16 of 18

Map map = new HashMap();


map.put("SubreportStream",TestPrint.class.getResourceAsStream("companySubReport.jas
per")); InputStream is = TestPrint.class.getResourceAsStream("companyD.jasper");
JasperPrint print = JasperFillManager.fillReport(is,map,ds);

notice that i added to the master report (in it's parameter map) the input stream to the sub
report, this is my perffered way to link between the master and the subreport. notice that the
parameter map is a regular HashMap. and in the .jrxml file i refer to the parameter
$P{REPORT_PARAMETERS_MAP} as a Map ,and get the input stream from the map by
the key "SubreportStream".

If you'll look at the subreport you'll see that it is a regular report only that all the other bands
except the detail band are of width=0 and height=0.

Attachments: companySubReport.jrxml [SubreportExample1/companySubReport.jrxml]


companyD.jrxml [SubreportExample1/companyD.jrxml]

JasperReports Tutorial - Internationalization

JasperReports allows associating a java.util.ResourceBundle with the report design, either at


runtime, by using the new resourceBundle attribute or at runtime, by providing a value for the
REPORT_RESOURCE_BUNDLE build-in parameter.

If the report needs to be generated in a locale that is different from the current locale, then the
built-in REPORT_LOCALE parameter should be used to specify the runtime locale when
filling the report.

In order to ease the internationalization of the reports there is a special syntax available inside
report expressions that allows referencing String resources placed inside a
java.util.ResourceBundle object associated with the report. The $R{...} syntax is for
wrapping resource bundle keys in order to retrieve the value for that key.

For formatting messages in different languages, based on the report locale, there is a built-in
method inside the net.sf.jasperreports.engine.fill.JRCalculator associated with the report that
offers functionality similar to the java.text.MessageFormat class. This method is called msg()
and has 3 convenience signatures that allow using up to 3 message parameters in the
messages. There is also the build-in str() method which is the equivalent of the $R{...} syntax
inside the report expressions, giving access to the resource bundle content based on the report
locale.

In the generated output, the library now keeps information about the text run direction so that
documents generated in languages that have right-to-left writing (like Arabic and Hebrew)
could be rendered properly.

Check the I18nReport and UnicodeReport samples for details.

JasperReports Tutorial - Datasets


JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.jasperreports/wiki/Tutorial Page No 17 of 18

Charts and crosstabs sometimes need to use data which the containing report does not iterate
though directly at fill time. This would be the case with data sources that have fields which
could themselves be data sources for subreports.

In order to eliminate the need to use subreports in order to render a chart or a crosstab that
would be fed with the nested data, a new concept called a dataset was introduced. A dataset
is something between a data source and a subreport because it contains parameters, fields,
variables and groups, but no layout information. Check demos/samples/charts and the
Crosstabs sample.

JasperReports Tutorial - Charts

JasperReports now has built-in support for charts. There is a new, ready-to-use chart
component, although we already had images, text fields, subreports and other elements. This
greatly simplifies the way charts are included inside reports, because previously the user had
to completely rely on scriptlets in order to gather the chart data and render the chart using an
image element in the report template.

Now with the new chart component, the user only has to make the desired visual settings and
define the expressions that will help the engine build up the chart dataset in an incremental
fashion during the iteration through the report data source.

When including and configuring a chart component, there are three entities involved:

• the overall chart component;


• the chart dataset (groups chart data related settings);
• the chart plot (groups visual settings related to the way the chart items are rendered);
JasperReports currently supports the following types of charts:
Pie, Pie 3D, Bar, Bar 3D, XY Bar, Stacked Bar, Stacked Bar 3D, Line, XY Line,
Area, XY Area, Scatter Plot, Bubble, Time series, High Low Open Close,
Candlestick.

These types of charts use several types of datasets (each type of chart works with certain
types of datasets): Pie Dataset, Category Dataset, XY Dataset, Time Series, Time Period
Values, XYZ Dataset, High Low Dataset.

For all charts we can configure the following:

• border around all sides


• background color
• title
• title position (top, left, bottom, right)
• title font
• title color
• subtitle
• subtitle color
• subtitle font
• show/hide legend
• plot area background color
• plot area background transparency (alpha)
JB’s Collection http://jasperforge.org/sf/wiki/do/viewPage/projects.jasperreports/wiki/Tutorial Page No 18 of 18

• plot area foreground transparency (alpha)


• plot orientation (vertical, horizontal)
• axis labels

For all datasets we can configure:

• increment type (detail, column, page, group, report)


• increment group
• reset type (none, column, page, group, report)
• reset group Specific settings by chart type:

Pie 3D *depth factor Bar, XY Bar, Stacked Bar

• hide/show labels
• hide/show tick marks
• hide/show tick labels Bar 3D, Stacked Bar 3D
• hide/show labels
• x offset (3D effect)
• y offset (3D effect) Line, XY Line, Scatter Plot, Time series
• hide/show lines
• hide/show shapes Bubble
• scale type (both axes, domain axis, range axis) High Low Open Close
• hide/show close ticks
• hide/show open ticks Candlestick
• hide/show volume

JasperReports uses the JFreeChart library to render the charts. Details about how to use this
functionality can be found in the supplied JFreeChartsReport sample.

JasperReports Tutorial - Crosstabs

Crosstabs are a special type of table component in which both the rows and the columns are
dynamic. They are used to display aggregated data using tables with multiple levels of
grouping for both columns and groups.

For more details, check the crosstabs sample provided.