Course Jasper PDF
Course Jasper PDF
Course Jasper PDF
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
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:
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 fillthe 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:
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:
<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
Programmatic compilation.
Compilation through ANT task.
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.
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:
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:
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 is an instance of
net.sf.jasperreports.engine.JRVirtualizer object, and
REPORT_VIRTUALIZER
used for the page virtualization (optimize memory
consumption).
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 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.
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.
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.
<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>
<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 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:
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.
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>
Section Description
Title This section appears only once at the beginning of the report.
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:
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.
Unique identifier of
key A unique string value.
band element.
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.
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.
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.
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:
27 | P a g e
12. REPORT GROUPS
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
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.
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.
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
Determines the fill pattern used to fill the object. At the moment,
fill
the single value allowed is Solid.
Specifies scale for the images only. Possible values: Clip, FillFrame,
scaleImage
RetainShape, RealHeight, and RealSize.
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.
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.
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).
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).
<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:
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.
36 | P a g e