Course Jasper PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

1|P a g e

Table of Contents
1. INTRODUCTION .............................................................................................................................................. 3
What is a Report? ............................................................................................................................................... 3
Report Template ................................................................................................................................................. 3
Features of JasperReports .................................................................................................................................. 4
Jasper Managers Classes .................................................................................................................................... 5
2. LIFE CYCLE ...................................................................................................................................................... 6
3. CREATING AND USING DATABASE JDBC CONNECTIONS ............................................................................... 7
A JDBC connection .............................................................................................................................................. 7
The Dataset ......................................................................................................................................................... 9
4. DESIGNS ....................................................................................................................................................... 12
Creating a JRXML Report Template .................................................................................................................. 12
5. COMPILING REPORT DESIGN ....................................................................................................................... 13
Programmatic Compilation of JRXML ............................................................................................................... 13
Preview Compiled Report Template ................................................................................................................. 13
6. EXPORTING REPORTS ................................................................................................................................... 14
7.
REPORTS PARAMETERS ................................................................................................................................ 15
Parameter Declaration ..................................................................................................................................... 15
Built-in Parameters ........................................................................................................................................... 15
8. REPORT FIELDS ............................................................................................................................................. 17
Field Declaration ............................................................................................................................................... 17
Sort Fields ......................................................................................................................................................... 18
Sorted Report Example ..................................................................................................................................... 18
9.
REPORT EXPRESSION.................................................................................................................................... 19
Expression Declaration ..................................................................................................................................... 19
Conditional Expressions .................................................................................................................................... 20
10.
REPORT VARIABLES ...................................................................................................................................... 21
Report variables ................................................................................................................................................ 21
Built-In Report Variables ................................................................................................................................... 22
11. REPORT SECTIONS .................................................................................................................................... 23
Main Sections ................................................................................................................................................... 23
Section Elements .............................................................................................................................................. 25
Section Attributes ............................................................................................................................................. 27
.21 REPORT GROUPS ...................................................................................................................................... 28
Group Attributes ............................................................................................................................................... 28
13. REPORT FONTS ........................................................................................................................................ 30
Report Fonts ..................................................................................................................................................... 30
Font Attributes ................................................................................................................................................. 30
Font Types ........................................................................................................................................................ 31
14. REPORT STYLES ........................................................................................................................................ 32
Style Properties................................................................................................................................................. 32
Conditional Styles ............................................................................................................................................. 33
Style Templates ................................................................................................................................................ 33
Example ............................................................................................................................................................ 34
15.
CREATE SUBREPORTS ................................................................................................................................... 35
<subreport> Element ........................................................................................................................................ 35

2|P a g e
1. INTRODUCTION

What is a Report?

A report is a nicely formatted way of presenting the data that you have entered. Reports
are all about querying a database and displaying the results in a nice format. Data in the
database may be displayed just as is, that is, in hundreds of pages. However, most of
the time, reports are used to grasp information out of a bunch of data. This is mainly
done by charts which are graphical representations of information. When the data is
processed to fill out a report, calculations are done over the specific fields of the entries.
The results appear as bars or pies in a chart or as text at the end of the report.

3|P a g e
Report Template
Generally, the following layout is adopted to generate reports by most of the commercial
report generating tools.

TITLE

PAGEHEADER

COLUNHEADER

DETAIL

COLUMNFOOTER

PAGEFOOTER

SUMMARY

Following are the descriptions of each element mentioned in the diagram:

Element Description
title Title of the report is written in this part.
pageHeader PageHeader may contain date and time information and/or
organization name. This appears at the top of each page.
columnHeader ColumnHeader lists the names of those specific fields, which you want
to display in the report.
detail Detail is the part where entries of the specific fields (listed in
columnHeader)
columnFooter ColumnFooter may display summation of any of the field.
pageFooter PageFooter may contain page count information. It appears at the
bottom of each page.
Summary contains information inferred from "detail" part.
summary

Features of JasperReports
Some of the significant features of JasperReports are:

 It has a flexible report layout.



 It can accept data from the multiple data sources.

 It can generate sub-reports.

 Results exporting: There are a wide range of formats, which your report can be
exported to, such as: HTML, Text, PDF, MS Excel, RTF, ODT, Comma-separated
values, XML, or image.

4|P a g e
Jasper Managers Classes
There are number of classes, which will be used to compile a JRXML report design, to fill
a report, to print a report, to export to PDF, HTML & XML files, view the generated
reports, and report design.

5|P a g e
2. LIFE CYCLE

As shown in the image, the life cycle has the following distinct phases:

 Designing the report: In this step, we create the JRXML file, which is an XML
document that contains the definition of the report layout. We can use any text
editor or iReportDesigner to manually create it. If iReportDesigner is used, the
layout is designed in a visual way, hence real structure of the JRXML can be
ignored.

 Compiling the report: In this step, JRXML is compiled in a binary object called a
Jasper file (*.jasper). This compilation is done for performance reasons. Jasper
files are what you need to ship with your application in order to run the reports.

 Executing the report (Filling data into the report): In this step, data from
the application is filled in the compiled report.
The class net.sf.jasperreports.engine.JasperFillManager provides necessary
functions to fillthe data in the reports. A Jasper print file (*.jrprint) is created,
which can be used either to print or export the report.

 Exporting the report to desired format: In this step, we can export the Jasper
print file created in the previous step to any format using JasperExportManager.
As Jasper provides various forms of exports, hence with the same input, we can
create multiple representations of the data.

6|P a g e
3. CREATING AND USING
DATABASE JDBC CONNECTIONS
A JDBC connection

A JDBC connection allows you to use a relational DBMS (or, in general, whatever
databases are accessible through a JDBC driver) as a data source. To set a new JDBC
connection, click the New button in the Connections/Datasources dialog box (shown
earlier in “DataAdapter Wizard”) to open the interface for creation of a new connection
(or data source). From the list, select Database JDBC connection to bring up the window
shown in “Configuring a JDBC Connection”.
To edit the connection dataBase, click File -> New -> DataAdapter

Figure-1 Figure-2

Figure-3

7|P a g e
In the JDBC Driver field, you specify the name of the JDBC driver to use for the
connection to the database. The combo box proposes the names of the most common
JDBC drivers (see “JDBC Drivers List”).

Figure-4

It is possible to automatically construct the JDBC URL to use the connection to the
database by inserting the server name and the database name in the correct text fields.
Enter a username and password to access the database. By means of a check box
option, you can save the password for the connection.

After you have inserted all the data, it is possible to verify the connection by clicking
the Test button. If everything is okay, the dialog box shown in “Test Confirmation
Dialog”

Figure-5

In general, the test can fail for a number reasons, the most frequent of which are:

 A ClassNotFoundError was thrown.


 The URL is not correct.
 Parameters are not correct for the connection (database is not found, the
username or password is wrong, etc.).

The ClassNotFoundError exception occurs when the required JDBC driver is not present
in the classpath. For example, suppose you want to create a connection to an Oracle
database. Jaspersoft Studio has no driver for this database, but you could be deceived
by the presence of the oracle.jdbc.driver.OracleDriverdriver in the JDBC drivers list
shown in the window for creating new connections. If you were to select this driver,
when you test the connection, the studio throws the ClassNotFoundException, as shown
in “ClassNotFoundError exception”.

Figure-6

8|P a g e
What you have to do is to add the JDBC driver for Oracle, which is a file named
ojdbc6.jar (or classes12.zip or classes11.zip for older versions) to the classpath (which is
where the JVM searches for classes). As Jaspersoft Studio uses its own class loader, it's
enough add the ojdbc6.jar file to the Jaspersoft Studio classpath, which is defined in
your Eclipse project; the same can be done for directories containing classes and other
resources.

Figure-6

The Dataset

Every report has a main dataset defined during its creation. But sometimes we need
fields that are not returned by a query from the main dataset, or the fields needed may
be in a different data source.
To create a dataset, right-click on the report root node in the outline view and
choose Create Dataset:

Figure-1

9|P a g e
Figure-2

Figure-3

10 | P a g e
Figure-4

11 | P a g e
4. DESIGNS

The JRXML templates (or JRXML files) in JasperReport are standard XML files, having an
extension of .jrxml. All the JRXML files contain tag <jasperReport>, as root element.
This in turn contains many sub-elements (all of these are optional). JasperReport
framework can handle different kinds of data sources. In this tutorial, we shall show how
to generate a basic report, just by passing a collection of Java data object (using Java
beans), to the JasperReport Engine. The final report shall display a list of people with the
categories including their names and countries.

The Following steps are covered in this chapter to describe — how to design a
JasperReport:

 Creating a JRXML Report Template 


Creating a JRXML Report Template


Create the JRXML file, which is jasper_report_template.jrxml
Here are the details of main fields in the above report template:

 <queryString>: This is empty (as we are passing data through Java Beans).
Usually contains the SQL statement, which retrieves the report result.

 <field name>: This element is used to map data from data sources or queries,
into report templates. name is re-used in the report body and is case-sensitive.

 <fieldDescription>: This element maps the field name with the appropriate
element in the XML file.

 <staticText>: This defines the static text that does not depend on any data
sources, variables, parameters, or report expressions.

 <textFieldExpression>: This defines the appearance of the result field.

 <band>: Bands contain the data, which is displayed in the report.

12 | P a g e
5. COMPILING REPORT DESIGN

We have generated the JasperReport template (JRXML file) in the previous


chapter. This file cannot be used directly to generate reports. It has to be
compiled to JasperReport' native binary format, called Jasper file. On compiling,
we transform JasperDesign object into JasperReport object:

Interface net.sf.jasperreports.engine.design.JRCompiler plays a central role


during compilation. This interface has several implementations depending on the
language used for report expressions, which can be written in Java, Groovy,
JavaScript, or any other scripting language as long as compiler implementation
can evaluate it at runtime.

We can compile JRXML file in the following two ways:

 Programmatic compilation.

 Compilation through ANT task.

Programmatic Compilation of JRXML


JasperReports API offers a facade class
net.sf.jasperreports.engine.JasperCompileManager for compiling a JasperReport.
This class consists of several public static methods for compiling report
templates. The source of templates can be files, input streams and/or memory
objects.

The contents of the JRXML file (jasper_report_template.jrxml) are as follows.


As a result of the above compilation, you will see that template file
jasper_report_template.jasper got generated.

Preview Compiled Report Template


The net.sf.jasperreports.view.JasperDesignViewer can be used to preview compiled
report templates and JRXML templates.

To move further, let's add a new target viewDesign to the above build.xml file, which
will allow us to preview the compiled report. Below is the revised build.xml:

The import file - baseBuild.xml is picked from chapter Environment Setup and should
be placed in the same directory as the build.xml.

13 | P a g e
6. EXPORTING REPORTS

Here, we shall see how to transform or export these reports into other formats such as PDF,
HTML, and XLS. Facade class net.sf.jasperreports.engine.JasperExportManager is provided to
achieve this functionality. Exporting means transforming the JasperPrint object (.jrprint file)
into different format.

The following code (JasperReportExport.java) demonstrates the exporting process of the


JasperReport document. The JasperExportManager provides methods to export a report into
PDF, HTML, and XML only. To export to the XLS format, we have used the class
net.sf.jasperreports.engine.export.JRXlsExporter. This code generates the following three
files:

 sample_report.pdf

 sample_report.html

 sample_report.xls


14 | P a g e
7. REPORTS PARAMETERS

The main input for filling a report are: report template, parameters, and data sources.
This chapter will describe the parameters and in the next chapter we will discuss the
data sources.

Parameter Declaration
Parameter declaration as follows:

<parameter name="exampleParameter" class="java.lang.String" />

 The Name Attribute


The name attribute of the <parameter> element is mandatory. It references the
parameter in report expressions by name. Parameter name should be a single word. It
should not contain any special characters like dot or comma.

 The Class Attribute


The class attribute is also mandatory and it specifies the class name for the parameter
values. Its default value is java.lang.String. This can be changed to any class available
at runtime. Irrespective of the type of a report parameter, the engine takes care of
casting in the report expressions in which the $P{} token is used, hence making the
manual casts is unnecessary.

The report parameter values are always packed in a java.util.Map object, which has the
parameter name as its key. Report parameters can be used in the query string of the
report, so as to further customize the data set, retrieved from the database. These act
like dynamic filters in the query that supplies data for the report.

Built-in Parameters
Following are the pre-defined report parameters, ready to use in the expressions:

Parameter Name Description

Contains a map with all user defined and built-in


REPORT_PARAMETERS_MAP
parameters.
This points to the user supplied class
REPORT_CONNECTION
java.sql.Connection, used for JDBC datasources.

This is a user supplied instance of JRDataSource


REPORT_DATA_SOURCE representing either one of the built-in data source
types or a user-defined one.

This is a java.lang.Integer value, allowing the users


REPORT_MAX_COUNT
to limit the records from datasource.

This points to

15 | P a g e
net.sf.jasperreports.engine.JRAbstractScriptlet and
REPORT_SCRIPTLET
contains an instance of the report scriptlet provided
by the user.

This a java.util.Locale instance, containing the


REPORT_LOCALE
resource bundle desired locale.

This points to java.util.ResourceBundle object and


REPORT_RESOURCE_BUNDLE
contains localized messages.

This is a java.util.TimeZone instance, used for the


REPORT_TIME_ZONE
date formatting.

This is an instance of
net.sf.jasperreports.engine.JRVirtualizer object, and
REPORT_VIRTUALIZER
used for the page virtualization (optimize memory
consumption).

This is a java.lang.ClassLoader instance to be used


REPORT_CLASS_LOADER during the report filling process to load resources
such as images, fonts, and sub-report templates.

If set to java.lang.Boolean.TRUE, the report will be


IS_IGNORE_PAGINATION generated on one long page and page break will not
occur.

16 | P a g e
8. REPORT FIELDS

Report fields are elements, which represent mapping of data between datasource and
report template. Fields can be combined in the report expressions to obtain the desired
output. A report template can contain zero or more <field> elements. When declaring
report fields, the data source should supply data corresponding to all the fields defined in
the report template.

Field Declaration
Field declaration is done as shown below:

<field name="FieldName" class="java.lang.String"/>

 The Name Attribute


The name attribute of the <field> element is mandatory. It references the field in report
expressions by name.

 The Class Attribute


The class attribute specifies the class name for the field values. Its default value is
java.lang.String. This can be changed to any class available at runtime. Irrespective of
the type of a report field, the engine takes care of casting in the report expressions in
which the $F{} token is used, hence making manual casts unnecessary.

 Field Description
The <fieldDesciption> element is an optional element. This is very useful when
implementing a custom data source. For example, we can store a key or some
information, by which we can retrieve the value of field from the custom data source at
runtime. By using the <fieldDesciption> element instead of the field name, you can
easily overcome restrictions of field-naming conventions when retrieving the field values
from the data source.

Following is a piece of code from our existing JRXML file (Chapter Report Designs).
Here, we can see usage of name, class, and fieldDescription elements.

<field name="country" class="java.lang.String">


<fieldDescription><![CDATA[country]]></fieldDescription>
</field>
<field name="name" class="java.lang.String">
<fieldDescription><![CDATA[name]]></fieldDescription>
</field>

17 | P a g e
Sort Fields
At the times when data sorting is required and the data source implementation doesn't
support it (for e.g. CSV datasource), JasperReports supports in-memory field-based data
source sorting. The sorting can be done using one or more <sortField> elements in the
report template.

If at least one sort field is specified, during report filling process, the data source is
passed to a JRSortableDataSource instance. This in turn, fetches all the records from
data source, performs in memory sort according to the specified fields, and replaces the
original data source.

The sort field name should be identical to the report field name. Fields used for sorting
should have types that implement java.util.Comparable. Natural order sorting is
performed for all fields except those of type java.lang.String (for String type, collator
corresponding to the report fill locale is used). When several sortFields are specified, the
sorting will be performed using the fields as sort keys in the order in which they appear
in the report template. The following example demonstrates the sorting feature.

Sorted Report Example


Let's add the <sortField> element to our existing report template (Chapter Report
designs). Let's sort field country in descending order. The revised report template
(jasper_report_template.jrxml) is as follows. Save it to C:\tools\jasperreports-5.0.1\test
directory:

<sortField name="country" order="Descending"/>


<sortField name="name"/>

18 | P a g e
9. REPORT EXPRESSION

Report expressions are the powerful features of JasperReports, which allow us to display
calculated data on a report. Calculated data is the data that is not a static data and is not
specifically passed as a report parameter or datasource field. Report expressions are
built from combining report parameters, fields, and static data. The Java language is
used for writing report expressions by default. Other scripting languages for report
expressions like Groovy scripting language, JavaScript, or BeanShell script are supported
by JasperReports compilers.

This chapter will explain you — how do report expressions work, assuming that they
have been written using the Java language only. In a JRXML report template, there are
several elements that define expressions as:

 <variableExpression>

 <initialValueExpression>

 <groupExpression>

 <printWhenExpression>

 <imageExpression>

 <textFieldExpression>

Expression Declaration
Basically, all report expressions are Java expressions, which can reference the report
fields, report variables, and report parameters.

 Field Reference in Expression


To use a report field reference in an expression, the name of the field must be put
between $F{and} character sequences, as shown below:

<textfieldexpression>
$F{Name}
</textfieldexpression>

Following is a piece of code from our existing JRXML file (chapter Report Designs):

<textFieldExpression class="java.lang.String">
<![CDATA[$F{country}]]>
</textFieldExpression>

19 | P a g e
 Variable Reference in Expression
To reference a variable in an expression, we must put the name of the variable between
$V{and} as shown in the example given below:

<textfieldexpression>
"Total height : " + $V{SumOfHeight} + " ft."
</textfieldexpression>

 Parameter Reference in Expression


To reference a parameter in an expression, the name of the parameter should be put
between $P{and} as shown in the example given below:

<textfieldexpression>
"ReportTitle : " + $P{Title}
</textfieldexpression>

Conditional Expressions
JasperReports doesn't support if-else statements when defining variable expressions.
Instead, you can use the ternary operators {cond} ? {statement 1} : {statement
2}. This operator can be nested inside a Java expression to obtain the desired output
based on multiple conditions.

20 | P a g e
10. REPORT VARIABLES

Report variables

Report variables are special objects built on top of the report expression.

Report variables simplify the following tasks:

 Report expressions, which are heavily used throughout the report template.
These expressions can be declared only once by using the report variables.

 Report variables can perform various calculations based on the corresponding
expressions values such as count, sum, average, lowest, highest, variance, etc.

If variables are defined in a report design, then these can be referenced by new
variables in the expressions. Hence, the order in which the variables are declared in a
report design is important.
As seen above, <variable> element contains number of attributes. These attributes are
summarized below:

 The Name Attribute


Similar to parameters and fields, the name attribute of </variable> element is
mandatory. It allows referencing the variable by its declared name in the report
expressions.

 The Class Attribute


The class attribute is also mandatory that specifies the class name for the variable
values. Its default value is java.lang.String. This can be changed to any class available in
the classpath, both at the report-compilation time and the report filling time. The engine
takes care of type-casting in report expressions where the $V{} token is used, hence
manual type-casting is not required.

 Calculation
This attribute determines — what calculation to perform on the variable when filling the
report. The following subsections describe all the possible values for the calculation
attribute of the <variable> element.

 Average: The variable value is the average of every non-null value of the variable
expression. Valid for numeric variables only.

 Count: The variable value is the count of non-null instances of the variable
expression.

 First: The variable value is the value of the first instance of the variable
expression. Subsequent values are ignored.

 Highest: The variable value is the highest value for the variable expression.

 Lowest: The variable value is the lowest value for the variable expression in the
report.

 Nothing: No calculations are performed on the variable.

21 | P a g e

 StandardDeviation: The variable value is the standard deviation of all non-null
values matching the report expression. Valid for numeric variables only.

 Sum: The variable value is the sum of all non-null values returned by the report
expression.

 System: The variable value is a custom calculation (calculating the value for that
variable yourself, using the scriptlets functionality of JasperReports).

 Variance: The variable value is the variance of all non-null values returned by
evaluation of the report variable's expression.

Built-In Report Variables


There are some built-in system variables, ready to use in expressions, as follows:

Variable Name Description

This variable's value is its current page number. It can be used


to display both the current page number and the total number of
PAGE_NUMBER
pages using a special feature of JasperReports text field
elements, the evaluationTime attribute.

COLUMN_NUMBER This variable contains the current column number.


This report variable contains the total number of records
REPORT_COUNT
processed.
This variable contains the number of records that were
PAGE_COUNT
processed when generating the current page.

This variable contains the number of records that were


COLUMN_COUNT
processed when generating the current column.

The name of this variable is derived from the name of the group
GroupName_COUNT it corresponds to, suffixed with the _COUNT sequence. This
variable contains the number of records in the current group.

22 | P a g e
11. REPORT SECTIONS

Main Sections
A report template in JasperReports has the following main sections:

<title></title>

<pageheader></pageheader>

<columnheader></columnheader>

<groupheader></groupheader>

<detail></detail>

<groupfooter></groupfooter>

<columnfooter></columnfooter>

<pagefooter></pagefooter>

<lastpagefooter></lastpagefooter>

<summary></summary>

<nodata></nodata<>

<background></background>

The following table summarizes each of the sections:

Section Description

Title This section appears only once at the beginning of the report.

This section appears at the beginning of each page in the


Page Header
generated document.

This section appears at the beginning of each column in the


Column Header generated document. If the report has only one column defined,
then column header and footer sections are ignored.

This section is introduced by a report group (chapter Groups).


Each time the grouping expression changes its value, the group
Group Header header section is printed above the detail section. In case, if
more than one group is defined, the group header is printed in
the order of group definition.

This section is repeated for each line of data supplied by the


Detail report's data source. The detail section can be made of multiple
bands.

23 | P a g e
Group Footer This section is introduced by a report group (chapter Groups).
The group footer section is printed below the detail section before
the value of the grouping expression changes. The group footer is
always printed for the last line of data in data source. In case, if
more than one group is defined, the group footer is printed in the
reverse order of group definition.
Column Footer This section appears at the bottom of each column. If the report's
column count is 1, then column header and footer sections are
ignored.
Page Footer This section appears at the bottom of each page.
Last Page Footer This section replaces the regular page footer on the last page of the
report. In case, the summary section is also present, then this
might not be the very last page of the document. This section is
sometimes useful when summary information has to be displayed
at the bottom of the last page.
Summary This section appears only once at the end of the report.

No Data This section is printed when the When No Data Print report
property is set to No Data Section. If the <noData> section is
defined in the report template, and if the data source is empty,
then the <noData> section will be the only one taken into
account at fill time, and its content will produce the report
output.
The background section is displayed on every page and cannot
Background overflow to the next page. Elements placed on this section are
evaluated at page initialization time and are displayed in the
background. All other page objects are displayed on top of the
background objects. This section is useful for creating page
watermarks.

24 | P a g e
Section Elements
All the above mentioned report sections are optional. But any report template will have
at least one such section. Each of these sections contains a single <band> element as it
is only sub-element. A <band> can contain zero or more following sub-elements:

<line>, <rectangle>, <ellipse>, <image>, <staticText>, <textField>, <subReport>, or


<elementGroup>

Each of these elements must contain a single <reportElement> as its first element
(except elementGroup). A <reportElement> determines how data is laid out for that
particular element. Unlike variables and parameters, report elements are not required to
have a name, because normally you do not need to obtain any individual element inside
a report template.

The table below summarizes the attributes of <reportElement>:

Attribute Description Valid Values

Specifies the x An integer value indicating the x


x coordinate of the coordinate of the element in
band element. pixels. This attribute is required.

Specifies the y An integer value indicating the y


y coordinate of the coordinate of the element in
band element. pixels. This attribute is required.

An integer value indicating the


Specifies the width of
width element width in pixels. This
the band element.
attribute is required.

An integer value indicating the


Specifies the height of
height element height in pixels. This
the band element.
attribute is required.

Unique identifier of
key A unique string value.
band element.

NoStretch (default): The element


will not stretch.
Specifies how does RelativeToTallestObject: The
the element stretch element will stretch to
stretchType
when the containing accommodate the tallest object in
band stretches its group.
RelativeToBand: The element will
stretch to fit the band's height.

25 | P a g e
Float: The element will move
depending on the size of the
surrounding elements.
FixRelativeToTop (default): The
Specifies the
element will maintain a fixed
element's position
positionType position relative to the band's
when the band
top.
stretches.
FixRelativeToBottom: The
element will maintain a fixed
position relative to the band's
bottom.

true (default): Repeated values


Specifies if repeated will be printed.
isPrintRepeatedValues
values are printed. false: Repeated values will not be
printed.
Specifies the
mode background mode of Opaque, Transparent
the element

Specifies if the
element should be
removed when it is
isRemoveLineWhenBlank blank and there are true, false
no other elements in
the same horizontal
space.

Specifies if the
element must be
printed in a whole
isPrintInFirstWholeBand band, that is, a band true, false
that is not divided
between report pages
or columns.

Specifies if the
element will be
isPrintWhenDetailOverFlows printed when the true, false
band overflows to a
new page or column.

Specifies that the


element will be
printWhenGroupChanges printed when the A string value.
specified group
changes.

26 | P a g e
Either a hexadecimal RGB value
preceded by the # character, or
Specifies the one of the following predefined
forecolor foreground color of values: black, blue, cyan,
the element. darkGray, gray, green, lightGray,
magenta, orange, pink, red,
yellow, white.

Specifies the
Same as Valid Values for
backcolor background color of
forecolor
the element.

Section Attributes
Following are the attributes of a report section:

 Height
Height of the section specifies the height in pixels for that particular section and is very
important in the overall report design.

 Print When Expression


A Boolean expression that determines whether the section should be printed or not.

 Split Allowed
A flag indicating whether the section is allowed to split when it does not fit on the
current page. If true, the section will be transferred to the next page. Note that in case,
the section does not fit on the next page, then the section will be split regardless of the
flag's value. splitType can take the following values:

 splitType="Stretch:" Splits stretched content. If the section stretches on the


current page (if the available space is less than declared height), the region that
is added to the original height is allowed to split onto the next page.

 splitType="Prevent:" Prevent split on first attempt. If the section does not fit on
the next page, the split occurs normally, as band split prevention is effective
only on the first split attempt.

 splitType="Immediate:" Split immediately. The band is allowed to split anywhere
except above, its topmost element.

27 | P a g e
12. REPORT GROUPS

Groups in JasperReports help to organize data on report in a logical manner. A report


group represents a sequence of consecutive records in the data source, which have
something in common, such as the value of a certain report fields. A report group is
defined by the <group> element. A report can have any number of groups. Once
declared, groups can be referred throughout the report.

A report group has three elements:

 Group expression: This indicates the data that must change to start a new data
group.

 Group header section: Helps place label at the beginning of the grouped data.

 Group footer section: Helps place label at the end of the grouped data.

During the iteration through the data-source at report-filling time, if the value of the
group expression changes, a group rupture occurs. These group ruptures cause the
corresponding <groupFooter> and <groupHeader> sections are inserted in the resulting
document.

Report group mechanism does not perform any sorting on the data supplied by the data
source. Data grouping works as expected only when the records in the data source are
already ordered according to the group expressions used in the report.

Group Attributes
The <group> element contains attributes that allow us to control how grouped data is
laid out. The attributes are summarized in table below:

Attribute Description

This is mandatory. It references the group in report


expressions by name. It follows the same naming
conventions that we mentioned for the report
name
parameters, fields, and report variables. It can be used
in other JRXML attributes when you want to refer a
particular report group.

When set to true, each data group will begin on a new


isStartNewColumn
column. Default value is false.

When set to true, each data group will begin on a new


isStartNewPage
page. Default value is false.

When set to true, the report page number will be reset


isResetPageNumber
every time a new group starts. Default value is false.

When set to true, the group header will be reprinted on


isReprintHeaderOnEachPage
every page. Default value is false.

28 | P a g e
Defines minimum amount of vertical space needed at
the bottom of the column in order to place the group
minHeightToStartNewPage
header on the current column. The amount is specified
in report units.

Renders position of the group footer on the page, as


well as its behavior in relation to the report sections
footerPosition that follow it. Its value can be: Normal, StackAtBottom,
ForceAtBottom, and CollateAtBottom. Default value is
Normal.

When set to true, prevents the group from splitting on


keepTogether
its first break attempt.

29 | P a g e
13. REPORT FONTS

A report contains text elements and each of these can have its own font settings. These
settings can be specified using the <font> tag available in the <textElement> tag. A
report can define a number of fonts. Once defined, they can be used as default or base
font settings for other font definitions throughout the entire report.

Report Fonts
A report font is a collection of font settings, declared at the report level. A report font
can be reused throughout the entire report template when setting the font properties of
text elements.

Report fonts are now deprecated. Do not use <reportFont/> elements declared within
the document itself. Use the <style/> element instead.

Font Attributes
Table below summarizes the main attributes of the <font> element:

Attribute Description
The font name, which can be the name of a physical font, a logical
fontName one, or the name of a font family from the registered
JasperReports font extensions.

size The size of the font measured in points. It defaults to 10.


isBold The flag specifying if a bold font is required. It defaults to false.

isItalic The flag specifying if an italic font is required. It defaults to false.

The flag specifying if the underline text decoration is required. It


isUnderline
defaults to false.
The flag specifying if the strikethrough text decoration is required.
isStrikeThrough
It defaults to false.

The name of an equivalent PDF font required by the iText library


pdfFontName
when exporting documents to PDF format.

The equivalent PDF character encoding, also required by the iText


pdfEncoding
library.

The flag that specifies whether the font should be embedded into
isPdfEmbedded the document itself. It defaults to false. If set to true, helps view
the PDF document without any problem.

30 | P a g e
Font Types
In JasperReports fonts can be categorized as:
 Logical Fonts: Five font types, which have been recognized by the Java platform
since version 1.0, are called logical fonts. These are - Serif, SansSerif,
Monospaced, Dialog, and DialogInput

 Physical Fonts: These fonts are the actual font libraries consisting of, for
example, TrueType or PostScript Type 1 fonts. The physical fonts may be Arial,
Time, Helvetica, Courier, or any number of other fonts, including international
fonts.

 Font Extensions: The JasperReports library can make use of fonts registered
on-the-fly at runtime, through its built-in support for font extensions. A list of
font families can be made available to the JasperReports using font extension.
These are made out of similarly looking font faces and supporting specific locales.

31 | P a g e
14. REPORT STYLES

JasperReports has a feature <style> which helps to control text properties in a report
template. This element is a collection of style settings declared at the report level.
Properties like foreground color, background color, whether the font is bold, italic, or
normal, the font size, a border for the font, and many other attributes are controlled by
<style> element. Styles can extend other styles, and add to, or override properties of
the parent style as well.

Style Properties
A <style> element has many attributes. Some of the most commonly used are listed in
the table given below:

Attribute Description

Is mandatory. It must be unique because it references the


name
corresponding report style throughout the report.
isDefault Indicates whether this style is the document's default style.
style Is a reference to the parent style.
Specifies the element's transparency. Possible values are Opaque
mode
and Transparent.
forecolor Is the foreground color of object.
backcolor Is the background color of object.

Determines the fill pattern used to fill the object. At the moment,
fill
the single value allowed is Solid.

radius Specifies the radius of the rectangle's corner arc.

Specifies scale for the images only. Possible values: Clip, FillFrame,
scaleImage
RetainShape, RealHeight, and RealSize.

Specifies the horizontal alignment. Possible values: Left, Center,


hAlign
Right, and Justified.

Specifies the vertical alignment. Possible values: Top, Middle, and


vAlign
Bottom.
Specifies the element's rotation. Possible values: None, Left, Right,
rotation
and UpsideDown.

Specifies the line spacing between lines of text. Possible values:


lineSpacing
Single, 1_1_2, Double.

markup Specifies the markup style for styled texts.

fontName Specifies the font name.

fontSize Specifies the font size.

32 | P a g e
isBold Indicates if the font style is bold.
isItalic Indicates if the font style is italic.
isUnderline Indicates if the font style is underline.
isStrikeThrough Indicates if the font style is strikethrough.
pdfFontName Specifies the related PDF font name.
pdfEncoding Specifies the character encoding for the PDF output format.
isPdfEmbedded Indicates if the PDF font is embedded.
pattern Specifies the format pattern for formatted texts.
Indicates if an empty string (whitespace) should be shown if the
isBlankWhenNull
expression evaluates to null.

Conditional Styles
In some situations, a style should be applied only when certain condition is met (for
example, to alternate adjacent row colors in a report detail section). This can be
achieved using conditional styles.

A conditional style has two elements:

 a Boolean condition expression



 a style

The style is used only if the condition evaluates to true.

Style Templates
We can make a set of reports with a common look by defining the style at a common
place. This common style template can then be referenced by the report templates. A
style template is an XML file that contains one or more style definitions. Style template
files used by convention the *.jrtx extension, but this is not mandatory.

A style template contains the following elements:

 <jasperTemplate>:This is the root element of a style template file.



 <template>: This element is used to include references to other template files.
The contents of this element are interpreted as the location of the referred
template file.

 <style>: This element is identical to the element with the same name from
report design templates (JRXML files), with the exception that a style in a style
template cannot contain conditional styles. This limitation is caused by the fact
that

33 | P a g e
Example
Let's try out the conditional styles and style templates. Let's add the <style> element
alternateStyle to our existing report template (Chapter Report designs).

<style name="alternateStyle" fontName="Arial" forecolor="red">


<conditionalStyle>
<conditionExpression>
<![CDATA[new Boolean($V{countNumber}.intValue() % 2 == 0)]]>
</conditionExpression>
<style forecolor="blue" isBold="true"/>
</conditionalStyle>
</style>

34 | P a g e
15. CREATE SUBREPORTS

Subreports are one of the nice features of the JasperReports. This feature allows
incorporating a report within another report, that is, one report can be a subreport of
another. Subreports help us keep report designs simple, as we can create many simple
reports and encapsulate them into a master report. Subreports are compiled and filled
just like normal reports. Any report template can be used as a subreport when
incorporated into another report template, without anything changed inside (of the
report template).

Subreports are like normal report templates. They are in fact


net.sf.jasperreports.engine.JasperReport objects, which are obtained after compiling a
net.sf.jasperreports.engine.design.JasperDesign object.

<subreport> Element
A <subreport> element is used when introducing subreports into master reports. Here is
the list of sub-elements in the <subreport> JRXML element.

 <reportElement>

 <parametersMapExpression> : This is used to pass a map containing report
parameters to the subreport. The map is usually obtained from a parameter in
the master report, or by using the built-in REPORTS_PARAMETERS_MAP
parameter to pass the parent report's parameters to the subreport. This
expression should always return a java.util.Map object in which the keys are the
parameter names.

 <subreportParameter> : This element is used to pass parameters to the
subreport. It has an attribute name, which is mandatory.

 <connectionExpression > : This is used to pass a java.sql.Connection to the
subreport. It is used only when the subreport template needs a database
connection during report filling phase.

 <dataSourceExpression> : This is used to pass a datasource to the subreport.
This datasource is usually obtained from a parameter in the master report or by
using the built-in REPORT_DATA_SOURCE parameter to pass the parent report's
datasource to the subreport.

 The elements (connectionExpression and dataSourceExpression) cannot be
present at the same time in a <subreport> element declaration. This is because
we cannot supply both a data source and a connection to the subreport. We must
decide on one of them and stick to it.

 <returnValue> : This is used to assign the value of one of the subreport's
variables to one of the master report's variables. This sub-element has attributes
as follows:

o subreportVariable: This attribute specifies the name of the subreport


variable whose value is to be returned.

35 | P a g e
o toVariable: This attribute specifies the name of the parent report variable
whose value is to be copied/incremented with the value from the
subreport.

o calculation: This attribute can take values: Nothing, Count, DistinctCount,


Sum, Average, Lowest, Highest, StandardDeviation, Variance. Default
value for attribute calculation is "Nothing".

o incrementerFactoryClass: This attribute specifies the factory class for


creating the incrementer instance.

 <subreportExpression> : This indicates where to find the compiled report


template for the subreport. This element has a class attribute. The class attribute
can take any of these values:java.lang.String, java.io.File, java.net.URL,
java.io.InputStream, net.sf.jasperreports.engine.JasperReport. Default value is
java.lang.String.

 isUsingCache: This is an attribute of the <subreport> element. This is a Boolean,
when set to true, the reporting engine will try to recognize previously loaded
subreport template objects, using their specified source. This caching
functionality is available only for subreport elements that have expressions
returning java.lang.String objects as the subreport template source, representing
file names, URLs, or classpath resources.

36 | P a g e

You might also like