The JasperReports Ultimate Guide Third Edition Jasper Reports 3

JasperReports-Ultimate-Guide-3

JasperReports-Ultimate-Guide-3

JasperReports-Ultimate-Guide-3

JasperReports-Ultimate-Guide-3

JasperReports-Ultimate-Guide-3

User Manual: Pdf

Open the PDF directly: View PDF PDF.
Page Count: 333

DownloadThe JasperReports Ultimate Guide Third Edition Jasper Reports-Ultimate-Guide-3
Open PDF In BrowserView PDF
THE JASPERREPORTS ULTIMATE GUIDE

PAGE I

THE JASPERREPORTS ULTIMATE GUIDE

The JasperReports Ultimate Guide Third Edition
Copyright © 2011 Jaspersoft Corporation. All rights reserved. Printed in the U.S.A.
Jaspersoft, the Jaspersoft logo, Jaspersoft iReport Designer, JasperReports Library,
JasperReports Server, Jaspersoft OLAP, and Jaspersoft ETL are trademarks and/or registered
trademarks of Jaspersoft Corporation in the United States and in jurisdictions throughout the
world. All other company and product names are or may be trade names or trademarks of
their respective owners.
This is version 0811-UGJ37-6 of the JasperReports Ultimate Guide.

PAGE II

THE JASPERREPORTS ULTIMATE GUIDE

TABLE OF CONTENTS
GETTING STARTED.............................................................................................1
INSTALLING JASPERREPORTS....................................................................................1
REQUIREMENTS.....................................................................................................1
X11/HEADLESS JAVA.............................................................................................3
BUILDING THE SOURCE FILES AND RUNNING THE SAMPLES.............................................3
ANT BUILD TOOL...............................................................................................................................3
BUILDING THE PROJECT FROM SOURCE FILES..........................................................................................4
RUNNING THE SAMPLES.......................................................................................................................4
HSQLDB DEMO DATABASE...............................................................................................................4

WORKING WITH REPORT TEMPLATES......................................................................6
CREATING REPORT TEMPLATES................................................................................6
REPORT DESIGN PREVIEW.......................................................................................7
LOADING AND STORING REPORT TEMPLATE FILES.........................................................8
COMPILING REPORT TEMPLATES.............................................................................10
EXPRESSIONS SCRIPTING LANGUAGE........................................................................10
REPORT COMPILERS............................................................................................11
A BRIEF HISTORY OF REPORT COMPILATION..........................................................................................12
CONFIGURATION PROPERTIES TO CUSTOMIZE REPORT COMPILATION............................................................13
JDT COMPILER–SPECIFIC CONFIGURATION PROPERTIES..........................................................................15

ANT TASKS........................................................................................................15
ANT TASKS FOR COMPILING REPORTS.....................................................................15
ATTRIBUTES OF THE REPORT TEMPLATE COMPILATION TASK......................................................................16
ANT TASK FOR DECOMPILING REPORTS................................................................................................17
ANT TASK FOR UPDATING REPORTS....................................................................................................17

FILLING REPORT TEMPLATES..............................................................................19
REPORTING DATA................................................................................................20
GENERATED REPORTS..........................................................................................21
FILLING ORDER (VERTICAL/HORIZONTAL FILLING).......................................................21
PAGE III

THE JASPERREPORTS ULTIMATE GUIDE

ASYNCHRONOUS REPORT FILLING...........................................................................22

HANDLING GENERATED REPORTS........................................................................24
LOADING AND SAVING GENERATED REPORTS.............................................................24
VIEWING REPORTS...............................................................................................25
PRINTING REPORTS..............................................................................................27
EXPORTING REPORTS...........................................................................................28

LARGE FILE SUPPORT.......................................................................................30
FILE VIRTUALIZER................................................................................................31
SWAP FILE VIRTUALIZER.......................................................................................31
IN-MEMORY GZIP VIRTUALIZER.............................................................................32

API OVERVIEW...............................................................................................33
NET.SF.JASPERREPORTS.ENGINE.DESIGN.JASPERDESIGN............................................................................33
NET.SF.JASPERREPORTS.ENGINE.JASPERREPORT.....................................................................................34
NET.SF.JASPERREPORTS.ENGINE.JASPERCOMPILEMANAGER........................................................................34
NET.SF.JASPERREPORTS.ENGINE.JASPERPRINT........................................................................................34
NET.SF.JASPERREPORTS.ENGINE.JRDATASOURCE...................................................................................34
NET.SF.JASPERREPORTS.ENGINE.JRRESULTSETDATASOURCE....................................................................35
NET.SF.JASPERREPORTS.ENGINE.DATA.JRBEANARRAYDATASOURCE AND
NET.SF.JASPERREPORTS.ENGINE.DATA.JRBEANCOLLECTIONDATASOURCE.....................................................35
NET.SF.JASPERREPORTS.ENGINE.DATA.JRXMLDATASOURCE......................................................................35
NET.SF.JASPERREPORTS.ENGINE.JREMPTYDATASOURCE..........................................................................35
NET.SF.JASPERREPORTS.ENGINE.JASPERFILLMANAGER..............................................................................36
NET.SF.JASPERREPORTS.ENGINE.JRABSTRACTSCRIPLET............................................................................36
NET.SF.JASPERREPORTS.ENGINE.JRDEFAULTSCRIPTLET............................................................................36
NET.SF.JASPERREPORTS.ENGINE.JASPERPRINTMANAGER...........................................................................37
NET.SF.JASPERREPORTS.ENGINE.JASPEREXPORTMANAGER ........................................................................37
NET.SF.JASPERREPORTS.ENGINE.JASPERRUNMANAGER

............................................................................37
NET.SF.JASPERREPORTS.VIEW.JRVIEWER..............................................................................................37
NET.SF.JASPERREPORTS.VIEW.JASPERVIEWER.........................................................................................38
NET.SF.JASPERREPORTS.VIEW.JASPERDESIGNVIEWER...............................................................................38
NET.SF.JASPERREPORTS.ENGINE.UTIL.JRLOADER.....................................................................................38
NET.SF.JASPERREPORTS.ENGINE.UTIL.JRSAVER.......................................................................................38
NET.SF.JASPERREPORTS.ENGINE.XML.JRXMLLOADER................................................................................38
NET.SF.JASPERREPORTS.ENGINE.XML.JRPRINTXMLLOADER........................................................................39

REPORT TEMPLATE STRUCTURE..........................................................................40
JRXML...........................................................................................................40
XSD REFERENCE...............................................................................................40
JRXML ENCODING.............................................................................................41
REPORT TEMPLATE PROPERTIES.............................................................................42
PAGE IV

THE JASPERREPORTS ULTIMATE GUIDE

REPORT NAME................................................................................................................................ 43
LANGUAGE..................................................................................................................................... 43
COLUMN COUNT.............................................................................................................................. 43
PRINT ORDER................................................................................................................................. 43
PAGE SIZE..................................................................................................................................... 44
PAGE ORIENTATION..........................................................................................................................44
PAGE MARGINS............................................................................................................................... 45
COLUMN SIZE AND SPACING...............................................................................................................45
EMPTY DATA SOURCE BEHAVIOR........................................................................................................45
TITLE AND SUMMARY SECTION PLACEMENT............................................................................................46
COLUMN FOOTER PLACEMENT............................................................................................................46
SCRIPTLET CLASS............................................................................................................................ 46
RESOURCE BUNDLE..........................................................................................................................47
MISSING RESOURCES BEHAVIOR.........................................................................................................47
PAGINATION.................................................................................................................................... 47
FORMATTING NUMBERS, DATES, AND TIMES...........................................................................................47

CUSTOM PROPERTIES...........................................................................................48
IMPORTING PACKAGES..........................................................................................49
STYLES.............................................................................................................49
REPORT STYLE NAME...................................................................................................................... 51
DEFAULT REPORT STYLE...................................................................................................................51
CASCADING REPORT STYLES..............................................................................................................51
CONDITIONAL STYLES....................................................................................................................... 51
REFERENCING A REPORT STYLE..........................................................................................................53
STYLE TEMPLATES............................................................................................................................ 53

REPORTING DATA............................................................................................56
EXPRESSIONS.....................................................................................................56
SYNTAX......................................................................................................................................... 57
CALCULATOR.................................................................................................................................. 58
BUILT-IN FUNCTIONS........................................................................................................................ 59
CONDITIONAL EXPRESSIONS............................................................................................................... 59

PARAMETERS......................................................................................................60
PARAMETER NAME........................................................................................................................... 60
PARAMETER CLASS.......................................................................................................................... 61
PROMPTING FOR PARAMETER VALUES..................................................................................................61
PARAMETER CUSTOM PROPERTIES.......................................................................................................61
PARAMETER DEFAULT VALUE.............................................................................................................62
BUILT-IN REPORT PARAMETERS..........................................................................................................62

DATA SOURCES..................................................................................................67
JDBC DATA SOURCE......................................................................................................................68
JAVABEANS DATA SOURCES..............................................................................................................69
MAP-BASED DATA SOURCES.............................................................................................................71
TABLEMODEL DATA SOURCE.............................................................................................................71
XML DATA SOURCES...................................................................................................................... 72
PAGE V

THE JASPERREPORTS ULTIMATE GUIDE

CSV DATA SOURCES...................................................................................................................... 75
XLS DATA SOURCES....................................................................................................................... 76
EMPTY DATA SOURCES.....................................................................................................................76
REWINDABLE DATA SOURCES.............................................................................................................77
DATA SOURCE PROVIDER..................................................................................................................77

REPORT QUERIES................................................................................................78
SQL QUERIES............................................................................................................................... 78
STORED PROCEDURES...................................................................................................................... 81
QUERY EXECUTER API.................................................................................................................... 81
SQL QUERY EXECUTER...................................................................................................................83
XPATH QUERY EXECUTER.................................................................................................................83
HIBERNATE QUERY EXECUTER............................................................................................................84
MDX QUERY EXECUTER.................................................................................................................. 86
XMLA QUERY EXECUTER................................................................................................................ 91
EJB QL/JPA QUERY EXECUTER......................................................................................................93

FIELDS..............................................................................................................95
FIELD NAME................................................................................................................................... 96
FIELD CLASS..................................................................................................................................96
FIELD DESCRIPTION..........................................................................................................................97
CUSTOM FIELD PROPERTIES...............................................................................................................97
SORT FIELDS.................................................................................................................................. 97

VARIABLES.........................................................................................................98
VARIABLE NAME.............................................................................................................................. 99
VARIABLE CLASS............................................................................................................................. 99
RESET TYPE...................................................................................................................................99
RESET GROUP.............................................................................................................................. 100
INCREMENT TYPE........................................................................................................................... 100
INCREMENT GROUP........................................................................................................................ 100
CALCULATIONS.............................................................................................................................. 100
INCREMENTERS.............................................................................................................................. 102
BUILT-IN REPORT VARIABLES...........................................................................................................103

DATA FILTERS..................................................................................................104

REPORT SECTIONS.........................................................................................105
BAND CONTENT................................................................................................105
BAND HEIGHT...................................................................................................106
PREVENTING BAND SPLIT....................................................................................106
SKIPPING BANDS...............................................................................................106
MAIN SECTIONS................................................................................................107
TITLE.......................................................................................................................................... 107
PAGE HEADER.............................................................................................................................. 108
COLUMN HEADER.......................................................................................................................... 108
DETAIL........................................................................................................................................ 108
COLUMN FOOTER........................................................................................................................... 108
PAGE VI

THE JASPERREPORTS ULTIMATE GUIDE

PAGE FOOTER.............................................................................................................................. 108
SUMMARY.................................................................................................................................... 108
LAST PAGE FOOTER.......................................................................................................................108
BACKGROUND............................................................................................................................... 109
NO DATA..................................................................................................................................... 109

DATA GROUPING...............................................................................................109
GROUP NAME............................................................................................................................... 110
STARTING A NEW PAGE OR COLUMN WHEN A GROUP BREAKS................................................................111
RESETTING PAGE NUMBER.............................................................................................................. 111
GROUP HEADER............................................................................................................................ 111
GROUP FOOTER............................................................................................................................ 111
PREVENTING GROUP SPLIT..............................................................................................................112

MULTI-BAND SECTIONS.......................................................................................113

REPORT ELEMENTS........................................................................................114
REPORT ELEMENT PROPERTIES............................................................................114
ELEMENT KEY............................................................................................................................... 115
STYLE......................................................................................................................................... 115
ABSOLUTE POSITION.......................................................................................................................115
RELATIVE POSITION........................................................................................................................ 115
ELEMENT SIZE.............................................................................................................................. 116
ELEMENT COLOR........................................................................................................................... 116
ELEMENT TRANSPARENCY................................................................................................................117
SKIPPING ELEMENT DISPLAY............................................................................................................ 117
REPRINTING ELEMENTS ON SECTION OVERFLOWS.................................................................................117
SUPPRESSING REPEATING VALUES DISPLAY.........................................................................................117
REMOVING BLANK SPACE................................................................................................................119
STRETCH BEHAVIOR....................................................................................................................... 121

CUSTOM ELEMENT PROPERTIES............................................................................121
TEXT ELEMENTS................................................................................................123
HORIZONTAL ALIGNMENT..................................................................................................................123
VERTICAL ALIGNMENT..................................................................................................................... 123
ROTATING TEXT............................................................................................................................ 123
LINE SPACING............................................................................................................................... 124
STYLED TEXT............................................................................................................................... 124
FONTS AND UNICODE SUPPORT........................................................................................................124
STATIC TEXTS............................................................................................................................... 130
TEXT FIELDS................................................................................................................................ 131
STYLED TEXT AND MARKUP TEXT......................................................................................................134
TEXT MEASURING AND TRUNCATION...................................................................................................136

GRAPHIC ELEMENTS...........................................................................................138
STRETCH BEHAVIOR....................................................................................................................... 139
BORDER STYLE............................................................................................................................. 139
BACKGROUND FILL STYLE................................................................................................................140
LINES.......................................................................................................................................... 140
PAGE VII

THE JASPERREPORTS ULTIMATE GUIDE

RECTANGLES................................................................................................................................ 140
ELLIPSES..................................................................................................................................... 141
IMAGES........................................................................................................................................ 141
CHARTS AND GRAPHICS.................................................................................................................. 148

BOX ELEMENTS.................................................................................................149
BORDER STYLE............................................................................................................................. 150
BORDER COLOR............................................................................................................................ 150
BOX PADDING............................................................................................................................... 150

HYPERLINKS, ANCHORS, AND BOOKMARKS..............................................................150
CUSTOM HYPERLINKS..................................................................................................................... 154
ANCHORS..................................................................................................................................... 155
BOOKMARKS................................................................................................................................. 155

ELEMENT GROUPS.............................................................................................155
FRAMES..........................................................................................................156
PAGE BREAKS AND COLUMN BREAKS.....................................................................157
GENERIC ELEMENTS...........................................................................................157
GENERIC ELEMENT PARAMETERS...................................................................................................... 159
GENERIC ELEMENT EXPORT HANDLERS..............................................................................................160

SUBREPORTS................................................................................................161
SUBREPORT OVERVIEW.......................................................................................161
CACHING SUBREPORTS................................................................................................................... 163

SUBREPORT PARAMETERS...................................................................................163
SUBREPORT DATA SOURCE.................................................................................164
RETURNING VALUES FROM SUBREPORTS.................................................................165
MASTER REPORT VARIABLE............................................................................................................. 166
USING RETURNED VALUES...............................................................................................................166
CUSTOM INCREMENTERS..................................................................................................................166

SUBREPORT RUNNERS........................................................................................166

DATASETS....................................................................................................169
MAIN DATASET.................................................................................................169
SUBDATASETS...................................................................................................169
DATASET RUNS.................................................................................................170

CHARTS.......................................................................................................172
CHART PROPERTIES...........................................................................................173
CHART RENDERING........................................................................................................................ 174
CHART TITLE AND SUBTITLE.............................................................................................................174
CHART LEGEND............................................................................................................................. 175
CHART CUSTOMIZER AND CHART THEME.............................................................................................175

CHART DATASETS..............................................................................................176
PAGE VIII

THE JASPERREPORTS ULTIMATE GUIDE

CHART DATASET OVERVIEW.............................................................................................................176
PIE DATASET................................................................................................................................ 178
CATEGORY DATASET...................................................................................................................... 179
XY DATASET................................................................................................................................ 180
TIME SERIES DATASET....................................................................................................................180
TIME PERIOD DATASET................................................................................................................... 181
XYZ DATASET..............................................................................................................................182
HIGH-LOW DATASET...................................................................................................................... 183
VALUE DATASET............................................................................................................................ 184
CHART ITEM HYPERLINKS................................................................................................................ 184

CHART PLOTS..................................................................................................185
CHART PLOT OVERVIEW..................................................................................................................185
PIE PLOT..................................................................................................................................... 187
PIE 3D PLOT............................................................................................................................... 187
BAR PLOT.................................................................................................................................... 188
BAR 3D PLOT.............................................................................................................................. 188
LINE PLOT................................................................................................................................... 189
AREA PLOT.................................................................................................................................. 190
SCATTER PLOT............................................................................................................................. 190
BUBBLE PLOT............................................................................................................................... 190
TIME SERIES PLOT........................................................................................................................ 191
HIGH-LOW PLOT........................................................................................................................... 192
CANDLESTICK PLOT........................................................................................................................ 192
METER PLOT................................................................................................................................ 193
THERMOMETER PLOT...................................................................................................................... 194
MULTI-AXIS PLOT........................................................................................................................... 196
AXIS FORMAT............................................................................................................................... 196

CHART TYPES...................................................................................................197
PIE CHART................................................................................................................................... 197
PIE 3D CHART............................................................................................................................. 197
BAR CHART.................................................................................................................................. 197
BAR 3D CHART............................................................................................................................ 198
XY BAR CHART............................................................................................................................ 198
STACKED BAR CHART.....................................................................................................................198
STACKED BAR 3D CHART............................................................................................................... 198
LINE CHART................................................................................................................................. 198
XY LINE CHART............................................................................................................................ 198
AREA CHART................................................................................................................................ 199
STACKED AREA CHART...................................................................................................................199
XY AREA CHART.......................................................................................................................... 199
SCATTER PLOT CHART................................................................................................................... 199
BUBBLE CHART............................................................................................................................. 199
TIME SERIES CHART...................................................................................................................... 200
HIGH-LOW-OPEN-CLOSE CHART......................................................................................................200
CANDLESTICK CHART...................................................................................................................... 200
METER CHART.............................................................................................................................. 200
PAGE IX

THE JASPERREPORTS ULTIMATE GUIDE

THERMOMETER CHART.................................................................................................................... 200
MULTI-AXIS CHART.........................................................................................................................200

CROSSTABS..................................................................................................202
CROSSTAB OVERVIEW........................................................................................202
REPEATING ROW AND COLUMN HEADERS............................................................................................202
COLUMN BREAK OFFSET................................................................................................................. 203
RUN DIRECTION............................................................................................................................ 203
IGNORE WIDTH.............................................................................................................................. 203

CROSSTAB PARAMETERS.....................................................................................203
CROSSTAB DATASETS.........................................................................................204
USING PRESORTED DATA................................................................................................................ 204

DATA GROUPING (BUCKETING).............................................................................205
BUCKET EXPRESSION......................................................................................................................205
BUCKET COMPARATOR AND SORT ORDER...........................................................................................206
ROW GROUPS.............................................................................................................................. 206
COLUMN GROUPS.......................................................................................................................... 208

MEASURES.......................................................................................................210
MEASURE NAME............................................................................................................................ 210
MEASURE TYPE............................................................................................................................. 210
MEASURE EXPRESSION................................................................................................................... 210
MEASURE CALCULATION AND CUSTOM INCREMENTERS............................................................................211
PERCENTAGES AND SECOND-PASS TYPES OF CALCULATIONS (DEPRECATED)..............................................211
BUILT-IN CROSSTAB TOTAL VARIABLES...............................................................................................211
CROSSTAB GOVERNOR....................................................................................................................212

CROSSTAB CELLS..............................................................................................213
CELL BACKCOLOR AND BORDER.......................................................................................................214
CROSSTAB HEADER CELL................................................................................................................214
DETAIL CELL................................................................................................................................ 214
TOTAL CELLS............................................................................................................................... 214
NO DATA CELL............................................................................................................................. 214

OTHER COMPONENTS......................................................................................216
LIST COMPONENT..............................................................................................216
BARCODE COMPONENTS......................................................................................218
BARBECUE................................................................................................................................... 218
BARCODE4J................................................................................................................................. 220

TABLE COMPONENT............................................................................................224

SCRIPTLETS..................................................................................................229
GLOBAL SCRIPTLETS..........................................................................................230
REPORT GOVERNORS.........................................................................................231

INTERNATIONALIZATION.....................................................................................233
PAGE X

THE JASPERREPORTS ULTIMATE GUIDE

REPORT EXPORTERS.......................................................................................234
EXPORTER INPUT...............................................................................................235
BATCH MODE EXPORT....................................................................................................................235

EXPORTER OUTPUT............................................................................................236
EXPORTER FILTERS............................................................................................236
ELEMENT ORIGIN FILTER................................................................................................................. 239
ELEMENT KEY FILTER.....................................................................................................................241

MONITORING EXPORT PROGRESS..........................................................................241
GRID EXPORTERS..............................................................................................242
CREATING GRID-FRIENDLY REPORT LAYOUTS......................................................................................242

FONT MAPPINGS...............................................................................................243
GRAPHICS2D EXPORTER....................................................................................244
JAVA PRINT SERVICE EXPORTER..........................................................................245
LOOKING UP A PRINTING SERVICE.....................................................................................................246
CONFIGURING THE PRINTER JOB....................................................................................................... 246
DISPLAYING PRINT DIALOGS.............................................................................................................247

PDF EXPORTER...............................................................................................247
FONT MAPPINGS............................................................................................................................ 248
BATCH MODE BOOKMARKS..............................................................................................................249
ENCRYPTED PDF..........................................................................................................................249
PDF VERSION AND COMPRESSION....................................................................................................250
WORD WRAP AND LINE BREAK POLICY..............................................................................................250
JAVASCRIPT ACTIONS.....................................................................................................................250
METADATA INFORMATION................................................................................................................. 251
RENDERING SVG USING SHAPES.....................................................................................................251
SECTION 508 COMPLIANCE............................................................................................................. 252

RTF EXPORTER...............................................................................................256
FONT MAPPINGS............................................................................................................................ 256

DOCX EXPORTER............................................................................................256
XML EXPORTER...............................................................................................257
EMBEDDING IMAGES........................................................................................................................257
OVERRIDING THE DTD LOCATION......................................................................................................258

HTML EXPORTER............................................................................................258
PERFECT ELEMENT ALIGNMENT.........................................................................................................258
FLOW-ORIENTED OUTPUT................................................................................................................259
HTML HEADER............................................................................................................................ 259
FONT MAPPINGS............................................................................................................................ 260
BACKGROUND COLOR..................................................................................................................... 261
TEXT WRAPPING........................................................................................................................... 261
PIXELS OR POINTS AND ZOOM.......................................................................................................... 261
WORKING WITH IMAGES...................................................................................................................262
PAGE XI

THE JASPERREPORTS ULTIMATE GUIDE

XHTML/CSS EXPORTER..................................................................................263
XLS/XLSX EXPORTERS....................................................................................263
CONFIGURING SHEETS.................................................................................................................... 264
FLOW-ORIENTED OUTPUT................................................................................................................265
CELL TYPES................................................................................................................................. 265
FORMAT PATTERN CONVERSIONS...................................................................................................... 266
FONT MAPPINGS............................................................................................................................ 266
FONT SIZE CORRECTION................................................................................................................. 266
BACKGROUND COLOR..................................................................................................................... 267
EXCEL COLOR PALETTE.................................................................................................................. 267

PPTX EXPORTER.............................................................................................267
ODT EXPORTER...............................................................................................267
ODS EXPORTER..............................................................................................268
CSV EXPORTER...............................................................................................268
PLAIN TEXT EXPORTER.......................................................................................269

CONFIGURATION FILES....................................................................................271
ADVANCED JASPERREPORTS............................................................................274
IMPLEMENTING DATA SOURCES.............................................................................274
CUSTOMIZING VIEWERS.......................................................................................275
USING JASPERREPORTS IN WEB ENVIRONMENTS......................................................276
COMPILING REPORT TEMPLATES........................................................................................................276
DEPLOYING REPORT TEMPLATES AND RESOURCES................................................................................277
DELIVERING IMAGES IN HTML FORMAT..............................................................................................277
PAGE-BY-PAGE HTML VIEWER.......................................................................................................278
SENDING PDF CONTENT TO THE BROWSER........................................................................................278
APPLET VIEWER............................................................................................................................ 278

EXTENSIONS SUPPORT........................................................................................279
EXTENSION REGISTRY.....................................................................................................................279
SPRING EXTENSION REGISTRY FACTORY.............................................................................................280

FONT EXTENSIONS.............................................................................................281
SIMPLE FONT EXTENSION TUTORIAL...................................................................................................282

CUSTOM COMPONENTS.......................................................................................285
CUSTOM COMPONENT USE CASES EXAMPLES......................................................................................285
CUSTOM COMPONENT IMPLEMENTATION OVERVIEW................................................................................286
SIMPLE BARCODE COMPONENT TUTORIAL............................................................................................288

INDEX..........................................................................................................293

PAGE XII

GETTING STARTED
This chapter is for those who have never used JasperReports. If you have already
installed JasperReports and used the samples, you can skip the chapter.

INSTALLING JASPERREPORTS
JasperReports is a content-rendering library, not a standalone application. It cannot run
on its own and must be embedded in another client- or server-side Java application.
JasperReports is a pure Java library and can be used on any platform that supports Java.
Being a library, JasperReports is completely agnostic about the environment in which it
is used for generating reports.
All JasperReports functionality is concentrated in a single JAR file, jasperreportsx.x.x.jar, available for download at the following URL:
http://sourceforge.net/project/showfiles.php?
group_id=36382&package_id=28579

Even though all its reporting functionality is available in this single JAR file,
JasperReports relies on other third-party libraries for related required functionality like
XML parsing, logging, and PDF and XLS generation.
Because JasperReports is a library and cannot run on its own, you do not really install it.
“Installing” JasperReports simply means downloading its JAR file and putting it into the
classpath of your application along with the other required JAR files.

REQUIREMENTS
JasperReports handles only reporting. It relies on third-party libraries and APIs to
perform needed functionality like XML parsing, database connectivity, PDF or XLS
output, and so on.
This section contains all the libraries that JasperReports may require, depending on the
functionality required by JasperReports’ parent application.
The two types of requirements for using JasperReports are the following:
 Absolute requirements, needed regardless of the module of JasperReports that is
actually used.
 Optional requirements, needed only for a specific JasperReports function. (If a
PAGE 1

THE JASPERREPORTS ULTIMATE GUIDE

certain function of JasperReports is not used by the parent application, then the
required libraries needed by that module can be skipped at deployment time.)
The following list details the requirements for using JasperReports:
 Java Virtual Machine (JVM), JRE 1.3 or higher
 One of the following for report compilation, depending on the report compiler
used:
* Eclipse JDT Java compiler (www.eclipse.org/jdt/index.php)
* JDK 1.3 or higher
* Jikes (http://jikes.sourceforge.net)
* Groovy (http://groovy.codehaus.org)
* JavaScript (http://www.mozilla.org/rhino)
* BeanShell (www.beanshell.org)
 JAXP 1.1 XML Parser
 Jakarta Commons Javaflow, sandbox version
(http://jakarta.apache.org/commons/sandbox/javaflow)
 Jakarta Commons Digester component, version 1.7 or later
(http://jakarta.apache.org/commons/digester)
 Jakarta Commons BeanUtils component, version 1.4 or later
(http://jakarta.apache.org/commons/beanutils)
 Jakarta Commons Collections component, version 2.1 or later
(http://jakarta.apache.org/commons/collections)
 Jakarta Commons Logging component, version 1.0 or later
(http://jakarta.apache.org/commons/logging)
 JDBC 2.0 driver
 iText (free Java PDF library by Bruno Lowagie and Paulo Soares), version 1.01 or
later (www.lowagie.com/iText)
 The following APIs for XLS:
* Jakarta POI, version 2.0 or later (http://jakarta.apache.org/poi)
* JExcelApi, version 2.6 or later ( http://jexcelapi.sourceforge.net)
 JFreeChart (free Java chart library), version 1.0.0 or later
(www.jfree.org/jfreechart)

PAGE 2

THE JASPERREPORTS ULTIMATE GUIDE

X11/HEADLESS JAVA
JasperReports relies on AWT rendering when generating reports, so it might not work if
you are using it in a server environment running UNIX/Linux without graphics support.
The application might raise errors such as “Can’t connect to X11 window server using
‘:0.0’.”
To solve this problem for JVM releases prior to 1.4, provide a pseudo–X server to
emulate a display environment. Following are some of these emulators:
 X Virtual Frame Buffer (Xvfb)
 Pure Java AWT (PJA)
 Virtual Network Computing (VNC)
The preferred solution for JRE 1.4 or higher is to use the new headless AWT toolkit.
This new feature allows you to use the J2SE API in a server-side Java application
without a GUI environment.
To specify the headless environment when using the Sun Microsystems reference
implementation, run your application with this property:
-Djava.awt.headless=true

BUILDING THE SOURCE FILES AND RUNNING THE SAMPLES
The best way to start working with JasperReports is to download the full project package
from the following SourceForge.net location:
http://sourceforge.net/project/showfiles.php?
group_id=36382&package_id=28579

The jasperreports-x.x.x-project.zip file available at this location contains all
the source files, required libraries, and freely available documentation, as well as a
complete set of sample applications and reports.
Download the archive and extract its contents to the directory of your choice on your
local machine. You’ll be able to see JasperReports in action without having to create a
Java application to embed JasperReports in.

ANT BUILD TOOL
Before using the JasperReports distribution files and samples, install the Ant tool on your
machine.
JasperReports relies heavily on the Ant build tool from the Apache Foundation
(http://ant.apache.org) to compile the source files, build the distribution files,
generate the Javadoc documentation, and run the samples. The Ant build tool will make

PAGE 3

THE JASPERREPORTS ULTIMATE GUIDE

working with the JasperReports library easier. Please refer to the Ant documentation for
installation instructions.

BUILDING THE PROJECT FROM SOURCE FILES
Once you have installed Ant, you can compile the source files, generate the Javadoc API
documentation, or build the distribution JAR files. To do this, execute the Ant tasks
declared in the build.xml file found in the root directory of the project tree.
To see details of each available task, launch the ant -p command from the command
prompt inside this root directory.

RUNNING THE SAMPLES
The JasperReports distribution package comes with a complete set of sample
applications and reports that show how each individual feature of the library can be used.
The samples are in the /demo/samples directory inside the project tree.

HSQLDB DEMO DATABASE
Some of the samples use data from an HSQLDB demo database supplied in the
/demo/hsqldb directory of the JasperReports distribution (www.hsqldb.org).
Before running those samples, start the HSQLDB database by going to the
/demo/hsqldb directory and launching ant runServer from the command prompt. To
look into the database content using a simple SQL client tool, launch the HSQLDB
Manager application by invoking ant runManager in the same directory after starting
the database.
To test a particular sample in the /demo/samples directory, go to the corresponding
sample subfolder and launch ant -p from the command line.
This displays a short description of what that sample demonstrates as well as a complete
list of Ant tasks available for use on the sample’s source files.
The following list gives the typical steps for running a sample:
1. Compile the sample’s Java source files by calling ant javac.
2. Compile the JRXML report templates used by the sample application with ant
compile.
3. Fill those report templates with data by calling ant fill.
4. View the result with ant view.
To export to other formats, simply use commands like ant pdf or ant html.
PAGE 4

THE JASPERREPORTS ULTIMATE GUIDE

These samples are used throughout this guide to illustrate features of the library.
Therefore make sure you can run the samples before reading the rest of this guide.

PAGE 5

WORKING WITH REPORT TEMPLATES
Report templates are standard in reporting applications. They define the layout of the
documents that the report-filling process produces.
Like other reporting engines, JasperReports uses report templates structured in multiple
sections. Each section type has its own characteristics and behavior. Section types
include title, summary, page and column headers and footers, group headers and footers,
and details. Each section is made of individual elements like lines, rectangles, static and
dynamic text fields, images, and charts.
Creating a report template is a two-phase process because of how JasperReports
evaluates report expressions, also known as formulas. The phases are as follows:
1. The initial report templates are compiled into a more digestible form before being
filled with data.
2. Various consistency checks are performed and information for evaluating
expressions at runtime is added.
The entry point into the JasperReports object model is the
net.sf.jasperreports.engine.design.JasperDesign class, whose instances

represent the source report templates, also called the raw material. These objects are
created by using the JasperReports API directly, through parsing of a JRXML file edited
by hand, or by using an UI design tool. Once compiled, these report-design objects are
transformed into compiled report templates in the form of
net.sf.jasperreports.engine.JasperReport objects.
Through compilation, the report templates are validated and put into a more read-only
form containing attached compiler data that will be used for expression evaluation during
the filling process.

CREATING REPORT TEMPLATES
There are two ways to create report templates:
 Creating net.sf.jasperreports.engine.design.JasperDesign objects
directly using the API
 Editing JRXML files using either a simple text editor, an XML editor, or a
specialized GUI tool
PAGE 6

THE JASPERREPORTS ULTIMATE GUIDE

The first option is recommended only in case the parent application that uses
JasperReports inside the reporting module needs to create report templates at runtime. In
most cases this is not needed because the report templates do not need to change with
every report execution, and hence static report templates could be used. Only the data
used to fill these static report templates is dynamic.
However, there are cases when the actual report template is the result of some user input.
The parent application might supply its users with a set of options when launching the
reports that might take the form of some simplified report designer or wizard. In such
cases, the actual report layout is not known or is not complete at design time, and can
only be put together after the user’s input is received.
The most common use case scenario that requires dynamically built or ad hoc report
templates (as we call them) is one in which the columns that are going to be present in a
table-like report layout are not known at design time. Instead, the user will give the
number of columns and their order inside the desired report at runtime.
Developers have to make sure that the applications they create really need ad hoc reports
and cannot rely solely on static report templates. Since dynamically built report
templates have to be compiled on the fly at runtime, they can result in a certain loss of
performance.
The second option for creating report templates is to edit JRXML files and use those
with the net.sf.jasperreports.engine.JasperCompileManager to prepare them
for filling with data. Because they are well structured and are validated against a public
XSD when parsed, these files can be easily edited using simple editors or specialized
XML editors.

REPORT DESIGN PREVIEW
The JasperReports library does not ship with an advanced GUI tool to help design
reports. It is the iReport project from Jaspersoft which provides a high quality and up-todate visual designer for creating report templates.
However, the library contains a very helpful visual component that lets you preview the
report designs as you build them.
The net.sf.jasperreports.view.JasperDesignerViewer class is a simple
Swing-based Java application that can load and display a report template either in its
JRXML form or its compiled form. Even though it is not a complex GUI application and
lacks advanced functionality like dragging and dropping visual report elements, it is a
very helpful tool. All the supplied samples were initially created using this design
viewer.
All the supplied samples already have Ant tasks in their build.xml files that will launch
this design viewer to display the report templates.

PAGE 7

THE JASPERREPORTS ULTIMATE GUIDE

There are two Ant tasks for each sample report: viewDesign and viewDesignXML. The
first one loads the compiled report template that is normally found in the *.jasper file.
The second one loads the JRXML report template, which is more useful since you can
edit the JRXML file and click the Reload button to immediately see the modification on
the screen.
To preview a sample report template if you have the Ant build tool installed on your
system, simply go to the desired sample directory and enter something like the following
from the command line:
>ant viewDesignXML

or
>ant viewDesign

By launching this command, you should see the window shown in Figure 2-1.

Figure 2-1. Report design preview tool

LOADING AND STORING REPORT TEMPLATE FILES
Both the net.sf.jasperreports.engine.design.JasperDesign and
net.sf.jasperreports.engine.JasperReport classes implement the
PAGE 8

THE JASPERREPORTS ULTIMATE GUIDE
java.io.Serializable interface. This allows users to store their report templates as
serialized objects either in their fully modifiable state ( JasperDesign objects) or in their
compiled form (JasperReport objects).

For serializing objects to files or output streams, the JasperReports library offers a utility
class named net.sf.jasperreports.engine.util.JRSaver.
To load serialized objects, you can rely on the supplied
net.sf.jasperreports.engine.util.JRLoader utility class, which exposes various
methods for loading objects from files, input streams, URLs, or classpath resources. This
utility class has a method called loadObjectFromLocation(String location), with
built-in logic to load a serialized object from a specified java.lang.String location
received as parameter. If this method is called, the program first tries to see if the
specified location is a valid URL. If it is not, it then tries to determine whether the
location points to an existing file on disk. If that also fails, the program tries to load the
serialized object from the classpath using the specified location as a classpath resource
name.
The library also exposes methods for parsing JRXML content into JasperDesign
objects or for producing JRXML content out of a JasperDesign or JasperReport
object.
The functionality is located in the following classes:


net.sf.jasperreports.engine.xml.JRXmlLoader



net.sf.jasperreports.engine.xml.JRXmlWriter

In certain cases in your application, you might want to manually load the JRXML report
template into a net.sf.jasperreports.engine.design.JasperDesign object
without immediately compiling it. You might do this for applications that
programmatically create report designs and use the JRXML form to store them
temporarily or permanently.
You can easily load net.sf.jasperreports.engine.design.JasperDesign objects
from JRXML report designs by calling one of the public static load() methods exposed
by the net.sf.jasperreports.engine.xml.JRXmlLoader class. This way, report
design objects can be loaded from JRXML content stored in a database field or other
input stream sources.
The library contains utility methods for parsing JRXML into report design objects and
vice versa. You can generate JRXML from an in-memory report design object.
As shown, sometimes report designs are generated automatically using the JasperReports
API. Report design objects obtained this way can be serialized for disk storage or
transferred over the network, but they also can be stored in JRXML format.

PAGE 9

THE JASPERREPORTS ULTIMATE GUIDE

You can obtain the JRXML representation of a given report design object by using one
of the public static writeReport() methods exposed by the
net.sf.jasperreports.engine.xml.JRXmlWriter utility class.

COMPILING REPORT TEMPLATES
Source report templates, created either by using the API or by parsing JRXML files, are
subject to the report compilation process before they are filled with data.
This is necessary to make various consistency validations and to incorporate into these
report templates data used to evaluate all report expressions at runtime.
The compilation process transforms
net.sf.jasperreports.engine.design.JasperDesign objects into
net.sf.jasperreports.engine.JasperReport objects. Both classes are
implementations of the same basic net.sf.jasperreports.engine.JRReport
interface. However, JasperReport objects cannot be modified once they are produced,
while JasperDesign objects can. This is because some modifications made on the

report template would probably require re-validation, or if a report expression is
modified, the compiler-associated data stored inside the report template would have to be
updated.
JasperDesign objects are produced when parsing JRXML files using the
net.sf.jasperreports.engine.xml.JRXmlLoader or created directly by the parent

application if dynamic report templates are required. The GUI tools for editing
JasperReports templates also work with this class to make in-memory modifications to
the report templates before storing them on disk.
A JasperDesign object must be subject to the report compilation process to produce a
JasperReport object.
Central to this process is the net.sf.jasperreports.engine.design.JRCompiler
interface, which defines two methods, one being the following:
public JasperReport compileReport(JasperDesign design) throws
JRException;

There are several implementations for this compiler interface depending on the language
used for the report expressions or the mechanism used for their runtime evaluation.

EXPRESSIONS SCRIPTING LANGUAGE
The default language for the report expressions is Java (see the discussion of the
language property in “Report Template Properties” on page 42), but report expressions
can be written in Groovy, JavaScript or any other scripting language as long as a report
compiler implementation that can evaluate them at runtime is available.

PAGE 10

THE JASPERREPORTS ULTIMATE GUIDE

JasperReports currently ships report compiler implementations for the Groovy scripting
language (http://groovy.codehaus.org), JavaScript (http://www.mozilla.org/rhino), and
the BeanShell scripting library (http://www.beanshell.org). The compiler implementation
classes are:


net.sf.jasperreports.compilers.JRGroovyCompiler

 net.sf.jasperreports.compilers.JavaScriptCompiler
 net.sf.jasperreports.compilers.JRBshCompiler
Historically, these compiler implementations used to be shipped as separate samples, but
now they are part of the core library.
For more details about those report compilers, check the
/demo/samples/beanshell, /demo/samples/groovy and the
/demo/samples/javascript samples distributed with the project source files.

REPORT COMPILERS
The report templates can be compiled using the desired report compiler implementation
by instantiating it and calling the compileReport() method mentioned previously.
Since the most common scenario is to use the Java language for writing report
expressions, default implementations of the report compiler interface are shipped with
the library and are ready to use. They generate a Java class from the report expressions
and store bytecode in the generated net.sf.jasperreports.engine.JasperReport
object for use at report-filling time.
The Java report compilers come in different flavors depending on the Java compiler used
to compile the class that is generated on the fly:
 net.sf.jasperreports.engine.design.JRJdtCompiler
 net.sf.jasperreports.engine.design.JRJdk13Compiler
 net.sf.jasperreports.engine.design.JRJdk12Compiler
 net.sf.jasperreports.engine.design.JRJavacCompiler
 net.sf.jasperreports.engine.design.JRJikesCompiler
To simplify the report-compilation process, the JasperReports API offers a facade class
(net.sf.jasperreports.engine.JasperCompileManager) for compiling reports.
This class has various public static methods for compiling report templates that come
from files, input streams, or in-memory objects. The facade class relies the report
template language to determine an appropriate report compiler.
The report compilation facade first reads a configuration property called
net.sf.jasperreports.compiler. to determine whether a compiler
implementation has been configured for the specific report language. If such a property
is found, its value is used as compiler implementation class name and the facade
PAGE 11

THE JASPERREPORTS ULTIMATE GUIDE

instantiates a compiler object and delegates the report compilation to it. By default,
JasperReports includes configuration properties that map the Groovy, JavaScript and
BeanShell report compilers to the groovy, javascript and bsh report languages,
respectively.
If the report uses Java as language and no specific compiler has been set for this
language, the report compilation facade employs a built-in fall back mechanism that
picks the best Java-based report compiler available in the environment in which the
report compilation process takes place.
The net.sf.jasperreports.engine.design.JRDefaultCompiler first reads the
configuration property called net.sf.jasperreports.compiler.class to allow
users to override its built-in compiler-detection logic by providing the name of the report
compiler implementation to use directly. More on configuration properties for
customizing report compilation can be found later in this chapter.
This facade first tries to see if the JDT compiler from the Eclipse Foundation is available
in the application’s classpath. If it is, the
net.sf.jasperreports.engine.design.JRJdtCompiler implementation is used.
The current JasperReports distribution ships the JDT compiler packed in the /lib/jdtcompiler.jar file.
If the JDT compiler is not available, the compilation facade then tries to locate the JDK
1.3–compatible Java compiler from Sun Microsystems. This is normally found in the
tools.jar file that comes with the JDK installation.
If the JDK 1.3–compatible Java compiler is not in the classpath, the fall back search
mechanism looks for the JDK 1.2–compatible Java compiler, also from Sun
Microsystems, in case the application is running in an environment that has a JDK
version prior to 1.3 installed. This is also found in the tools.jar file from the JDK
installation.
If all these fail, the last thing the fall back mechanism does is to try to launch the
javac.exe program from the command line in order to compile the temporarily
generated Java source file on the fly.

A BRIEF HISTORY OF REPORT COMPILATION
All these report compiler implementations are included for historical reasons. In the
beginning, JasperReports started with only the JDK 1.2–compatible report compiler.
Then the JDK 1.3–compatible report compiler was introduced. But both were slow. This
is why the net.sf.jasperreports.engine.design.JRJikesCompiler was created,
because the Jikes compiler proved to be up to ten times faster than the JDK-based Java
compiler.
However, compiling reports on the fly (in the cases in which dynamic report templates
were required) proved to be problematic, especially in a web environment, because all
the aforementioned compilers worked only with files on disk and required a temporary
PAGE 12

THE JASPERREPORTS ULTIMATE GUIDE

working directory to store the generated Java source files and the corresponding class
files during the report-compilation process. This is why a new implementation was added
—one that relied on the BeanShell library for runtime expression evaluation. BeanShell
does not produce Java bytecode and can work with in-memory scripts that it interprets at
runtime. With the net.sf.jasperreports.engine.design.JRBshCompiler,
deployment was simpler, but expression evaluation was slower and loss in performance
was noticeable.
The addition of the JDT-based report compiler makes the whole process both faster and
simpler to deploy, as it does not require files on disk and its performance is comparable
to Jikes. Runtime report compilation is not an issue anymore, and simply putting the
supplied /lib/jdt-compiler.jar file in the application’s classpath allows dynamic
report template creation without requiring any further settings.

CONFIGURATION PROPERTIES TO CUSTOMIZE REPORT COMPILATION
Because it is a library, JasperReports offers various mechanisms for letting users
customize its behavior. One of these mechanisms is a complete set of configuration
properties. The following paragraphs list all the configuration properties that customize
report compilation. You can learn more about how JasperReports can be configured in
“Configuration Files” on page 272.

net.sf.jasperreports.compiler.xml.
Such properties are used for indicating the name of the class that implements the
JRCompiler interface to be instantiated by the engine for a specific report language
when the default compilation is used through the JasperCompileManager facade The
value for such a configuration property can be the name of one of the built-in
implementations of this interface shipped with the library as listed previously, or the
name of a custom-made implementing class.
One can configure report compilers for custom report languages and override the default
compiler mappings by setting JasperReports properties of the form
net.sf.jasperreports.compiler. to the desired compiler
implementation class names. In particular, the mechanism that automatically chooses a
Java report compiler can be superseded by explicitly setting the
net.sf.jasperreports.compiler.java property to the name of one of the built-in
Java compiler classes or of a custom compiler implementation class.
Note that the classes implementing the JRCompiler interface can also be used directly in
the programs without having to call them through the facade JasperCompilerManager
class.

PAGE 13

THE JASPERREPORTS ULTIMATE GUIDE

net.sf.jasperreports.compiler.xml.validation
This was formerly known as the jasper.reports.compile.xml.validation system
property.
The XML validation, which is on by default, can be turned off by setting the
net.sf.jasperreports.compiler.xml.validation configuration property to
false. When turned off, the XML parser no longer validates the supplied JRXML
against its associated XSD. This might prove useful in some environments, although it is
not recommended.
When working with a Java class generating the type of a report compiler, further
customizations can be made using the following system properties, which only apply to
them.

net.sf.jasperreports.compiler.classpath
Formerly known as the jasper.reports.compile.class.path system property, this
supplies the classpath. JDK-based and Jikes-based compilers require that the classpath be
supplied as a parameter. They cannot use the current JVM classpath. The supplied
classpath resolves class references inside the Java code they are compiling.
This property is not used by the JDT-based report compiler, which simply uses the parent
application’s classpath during Java source file compilation.

net.sf.jasperreports.compiler.temp.dir
This was formerly known as the jasper.reports.compile.temp system property.
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
net.sf.jasperreports.compiler.temp.dir configuration property. This is used by
the JDT-based compiler only when it is requested that a copy of the on-the-fly generated
Java class be kept for debugging purposes as specified by the next configuration
property, because normally this report compiler does not work with files on disk.

net.sf.jasperreports.compiler.keep.java.file
This was formerly known as the jasper.reports.compile.keep.java.file system
property.
Sometimes, for debugging purposes, it is useful to have the generated *.java file or
generated script in order to fix 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, set the configuration property
net.sf.jasperreports.compiler.keep.java.file to true.

PAGE 14

THE JASPERREPORTS ULTIMATE GUIDE

JDT COMPILER–SPECIFIC CONFIGURATION PROPERTIES
The JRJdtCompiler report compiler can use special JasperReports configuration
properties to configure the underlying JDT Java compiler. This report compiler collects
all the JasperReports configuration properties (the ones usually set in the
jasperreports.properties file) that start with the org.eclipse.jdt.core. prefix
and passes them to the JDT Java compiler when compiling the generated Java class to
evaluate report expressions.
One of the uses of this mechanism is to instruct the JDT compiler to observe Java 1.5
code compatibility. To do so, the following properties should be set:
org.eclipse.jdt.core.compiler.source=1.5
org.eclipse.jdt.core.compiler.compliance=1.5
org.eclipse.jdt.core.compiler.codegen.TargetPlatform=1.5

This is demonstrated in the /demo/samples/java1.5 sample distributed with
JasperReports.

ANT TASKS
When the number of different report files that one has to deal with in a project is
significant, there is a need for automating repeating or re-occurring tasks that are to be
performed on those files.
From a design point of view, the most notable operation that needs to be performed on
report source files after they are finished and ready to be deployed is the report
compilation. Sometimes reports need to be decompiled in order to reproduce their
corresponding source files and perform additional design work on them, or when the
same modification needs to be performed identically on all reports.
For these re-occurring tasks, JasperReports provides built-in ready-to-use Ant task
definitions.

ANT TASKS FOR COMPILING REPORTS
Since report template compilation is more like a design-time job than a runtime one, a
custom Ant task has been provided with the library to simplify application development.
This Ant task is implemented by the
net.sf.jasperreports.ant.JRAntCompileTask class. Its syntax and behavior are
very similar to the built-in  Ant task.

The report template compilation task can be declared like this, in a project’s build.xml
file:

PAGE 15

THE JASPERREPORTS ULTIMATE GUIDE








In the preceding example, the lib should contain the jasperreports-x.x.x.jar file
along with its other required libraries.
You can then use this user-defined Ant task to compile multiple JRXML report template
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 TEMPLATE COMPILATION TASK
Following is the list of attributes that can be used inside the Ant report compilation task
to specify the source files, the destination directory, and other configuration properties:
srcdir: Location of the JRXML report template files to be compiled. Required unless
nested  elements are present.
destdir: Location to store the compiled report template files (the same as the source

directory by default).
compiler: Name of the class that implements the
net.sf.jasperreports.engine.design.JRCompiler interface to be used for

compiling the reports (optional).
xmlvalidation: Flag to indicate whether the XML validation should be performed on
the source report template files ( true by default).
tempdir: Location to store the temporarily 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 template compilation task supports nested  and 
elements, just like the Ant  built-in task.
To see this in action, check the /demo/samples/antcompile sample provided with the
project’s source files.

PAGE 16

THE JASPERREPORTS ULTIMATE GUIDE

ANT TASK FOR DECOMPILING REPORTS
Sometimes it happens that report templates are to be found only in their compiled form.
The source report template files might have been lost and we might have only the
compiled report template on which we need to make some modifications.
In such cases, the Ant task for decompiling report template files that JasperReports
provides becomes very handy. It is implemented by the
net.sf.jasperreports.ant.JRAntDecompileTask class and its declaration inside a
build.xml should be as follows:


In the above example, the classpath should contain the
jasperreports-x.x.x.jar file along with its other required
libraries.

This task works similarly to the report compilation task, but it does the reverse operation.
The files to be decompiled can be specified using the srcdir attribute for their root
folder or, for more sophisticated file match patterns, a nested  tag. The output
folder for the generated files is specified using the destdir attribute.
This task is demonstrated in the /demo/samples/antcompile sample provided with
the project source files.

ANT TASK FOR UPDATING REPORTS
Although JasperReports always guarantees backward compatibility of report templates
when upgrading to a newer version, sometimes tags or attributes in JRXML are
deprecated and replaced with newer ones that offer enhanced capabilities. So while the
deprecated attributes and tags still work, it is always advisable to use the latest syntax
and thus get rid of the deprecation warnings.
Upgrading a report template to the latest JasperReports syntax is very easy; all that needs
to be done is to load the report and save it again using the API's utility classes, such as
the JRXmlLoader or JRLoader and the JRXmlWriter.
This operation can be automated for any number of files using the Ant report update task
provided by the JasperReports library in the
net.sf.jasperreports.ant.JRAntUpdateTask class, which should have the
following definition in a build.xml file:




PAGE 17

THE JASPERREPORTS ULTIMATE GUIDE

This task is useful also in situations where the same modification needs to be applied on
a number of different report files. The required modifications can be performed using the
JasperReport API after the report design object has been loaded but before it is saved
again.
Custom implementations of the
net.sf.jasperreports.engine.util.ReportUpdater interface can be registered
with the Ant report update task using nested  tags, as seen in the
/demo/samples/antupdate sample provided with the project.

PAGE 18

FILLING REPORT TEMPLATES
The report-filling process is the most important piece of JasperReports library
functionality, because it manipulates sets of data to produce high-quality documents.
This is the main purpose of any reporting tool.
The following things should be supplied to the report-filling process as input:
 Report template (in the compiled form)
 Parameters
 Data source
The output is always a single, final document ready to be viewed, printed, or exported to
other formats.
The net.sf.jasperreports.engine.JasperFillManager class is usually used for
filling a report template with data. This class has various methods that fill report
templates located on disk, come from input streams, or are supplied directly as inmemory net.sf.jasperreports.engine.JasperReport objects.
The output produced always corresponds to the type of input received. That is, when
receiving a file name for the report template, the generated report is also placed in a file
on disk. When the report template is read from an input stream, the generated report is
written to an output stream, and so forth.
The various utility methods for filling the reports may not be sufficient for a particular
application—for example, loading report templates as resources from the classpath and
outputting the generated documents to files on disk at a certain location.
In such cases, consider manually loading the report template objects before passing them
to the report-filling routines using the
net.sf.jasperreports.engine.util.JRLoader utility class. This way, you can
retrieve report template properties, such as the report name, to construct the name of the
resulting document and place it at the desired disk location.
The report-filling manager class covers only the most common scenarios. However, you
can always customize the report-filling process using the library’s basic functionality just
described.

PAGE 19

THE JASPERREPORTS ULTIMATE GUIDE

REPORTING DATA
The JasperReports library is completely agnostic and makes no assumptions about where
the data it uses for filling the reports comes from. It is the responsibility of
JasperReports’ parent application to supply this data and handle the output generated by
the library.
JasperReports can make use of any data that the parent application might have for
generating reports because it relies on two simple things: the report parameters and the
report data source.
Report parameters are basically named values that are passed to the engine at reportfilling time. The report parameter values are always packed in a java.util.Map object,
which has the parameter names as its keys.
As for the data source, there are two different scenarios:
Normally, the engine works with an instance of the
net.sf.jasperreports.engine.JRDataSource interface, from which it extracts the

data when filling the report.
The facade class net.sf.jasperreports.engine.JasperFillManager has a full set
of methods that receive a net.sf.jasperreports.engine.JRDataSource object as
the data source of the report that is to be filled.
But there is another set of report-filling methods in this manager class that receive a
java.sql.Connection object as a parameter, instead of an expected data source object.
This is because reports are usually generated using data that comes from tables in
relational databases.
Users can put the SQL query needed to retrieve the report data from the database in the
report template itself. At runtime, the only thing the engine needs is a JDBC connection
object to connect to the desired relational database, execute the SQL query, and retrieve
the report data.
Behind the scenes, the engine still uses a special
net.sf.jasperreports.engine.JRDataSource object, but this is performed

transparently for the calling program.
The main difference between parameters and the data source is that parameters are
single-named values used inside report expressions for calculations or display, while the
data source represents tabular data made of virtual rows and columns that the engine uses
for iteration during the report-filling process.
JasperReports can make use of any application data because the JRDataSource interface
is very simple and easy to implement. It only has two methods:
 The next() method, which moves the record pointer to the next record in the
virtual tabular data
PAGE 20

THE JASPERREPORTS ULTIMATE GUIDE

 The getFieldValue() method, which retrieves the value for each column in the
current virtual record of the data source
The library ships with several implementations for the JRDataSource interface that
cover the most commonly used sources for filling reports using Java, such as collections
or arrays of JavaBeans, XML data, Swing table models, or JDBC result sets.
Provided with the project are several sample applications that fill the reports using data
from the supplied HSQLDB database server. Additionally, the
/demo/samples/datasource sample shows how to create custom data source
implementations and how to use some of the supplied data source implementations. Also
check the /demo/samples/xmldatasource to see how to use the XPath-based data
source implementation shipped with the library for reporting.

GENERATED REPORTS
The output of the report-filling process is always a pixel-perfect document, ready for
viewing, printing, or exporting to other formats. These documents come in the form of
net.sf.jasperreports.engine.JasperPrint objects, which are serializable. This
allows the parent application to store them or transfer them over the network if needed.
At the top level, a JasperPrint object contains some document-specific information,
like the name of the document, the page size, and its orientation (portrait or landscape).
Then it points to a collection of page objects
(net.sf.jasperreports.engine.JRPrintPage instances), each page having a
collection of elements that make up its content. Elements on a page are absolutely
positioned at x and y coordinates within that page and have a specified width and height
in pixels. They can be lines, rectangles, ellipses, images, or text, with various style
settings corresponding to their type.

FILLING ORDER (VERTICAL/HORIZONTAL FILLING)
JasperReports templates allow the detail section to be smaller than the specified page
width so that the output can be structured into multiple columns, like a newspaper.
When multiple-column report templates are used, the order used for filling those
columns is important (see Figure 3-1 on page 22).
There are two possible column orders (see the columnCount and printOrder
properties presented in “Report Template Properties”on page 42):
 Vertical, meaning that they run from top to bottom and then from left to right
 Horizontal, meaning that they first run from left to right and then from top to
bottom
When filling report templates horizontally, dynamic text fields inside the detail section
do not stretch to their entire text content, because this might cause misalignment on the
PAGE 21

THE JASPERREPORTS ULTIMATE GUIDE

horizontal axis of subsequent detail sections. The detail band actually behaves the same
as the page and column footers, preserving its declared height when horizontal filling is
used.

Figure 3-1. Multicolumn report print order

ASYNCHRONOUS REPORT FILLING
JasperReports provides the
net.sf.jasperreports.engine.fill.AsynchronousFillHandle class to be used

for asynchronous report filling. The main benefit of this method is that the filling process
can be canceled if it takes too much time. This can be useful, for example, in GUI
applications where the user would be able to abort the filling after some time has elapsed
and no result has been yet produced.
When using this method, the filling is started on a new thread. The caller is notified
about the progress of the filling process by way of listeners implementing the
net.sf.jasperreports.engine.fill.AsynchronousFillListener interface. The
listeners are notified of the outcome of the filling process, which can be success, failure,
or user cancellation. The handle is used to start the filling process, register listeners, and
cancel the process if wanted.
A typical usage of this handle is the following:
 The handle is created by calling the static
PAGE 22

THE JASPERREPORTS ULTIMATE GUIDE
AsynchronousFillHandle.createHandle() methods that take as arguments

the report object, the parameter map, and the data source or the database
connection to be used.

 One or more listeners are registered with the handle by calling the addListener()
method. In a GUI application, the listener could perform some actions to present to
the user the outcome of the filling process.
 The filling is started with a call to the startFill() method. In a GUI application,
this could be the result of some user action; the user can also be notified that the
filling has started and is in progress.
 The filling can be canceled by calling cancellFill() on the handle. In a GUI,
this would be the result of a user action.
 The listeners are notified when the process finishes. There are three events defined
for the listeners, only one of which will be called, depending on the outcome of the
filling:
* reportFinished(): Called when the filling has finished successfully; the
filled report is passed as a parameter. In a GUI, the user would be presented the
filled report or would be able to save/export it.
* reportFillError(): Called when the filling ends in error; the exception that
occurred is passed as a parameter.
* reportCancelled(): Called when the filling is aborted by the user.

PAGE 23

HANDLING GENERATED REPORTS
The output of the report-filling process is a pixel-perfect document made of multiple
pages, each containing a series of absolutely positioned and sized visual elements. The
document is an instance of the net.sf.jasperreports.engine.JasperPrint class,
and it is the responsibility of the parent application to make use of it once generated by
JasperReports.
JasperPrint objects can be serialized for storage or transfer over the network, viewed

using a built-in viewer component, or printed or exported to more popular document
formats like PDF, HTML, RTF, XLS, ODT, CSV, or XML.

LOADING AND SAVING GENERATED REPORTS
Once a net.sf.jasperreports.engine.JasperPrint object has been created as a
result of the report-filling process, you can serialize it and store it on disk, normally in a
*.jrprint file. We could say that this is the proprietary format in which JasperReports
stores its generated documents.
You can easily save and load JasperPrint objects to and from *.jrprint files or
other byte streams using the net.sf.jasperreports.engine.util.JRSaver and
net.sf.jasperreports.engine.util.JRLoader utility classes that the library
offers. The JRLoader has various methods for loading serialized objects from files,
URLs, input streams, or classpath resources. Its loadObjectFromLocation(String)
method is the most flexible because it has a built-in fall back mechanism that tries to
understand if the supplied java.lang.String location is a URL, file name, or classpath
resource; only after all these fail will it raise an error.
Sometimes it is more convenient to store generated documents in a text-based format like
XML instead of serialized JasperPrint objects. This can be achieved by exporting
those documents to XML using the
net.sf.jasperreports.engine.export.JRXmlExporter implementation. The
recommended file extension for these is *.jrpxml. The documents can be parsed back
into in-memory JasperPrint objects using the
net.sf.jasperreports.engine.xml.JRPrintXmlLoader utility class.
Exporting to XML is explained in detail in the “XML Exporter” section on page 258.

PAGE 24

THE JASPERREPORTS ULTIMATE GUIDE

VIEWING REPORTS
JasperReports provides a built-in viewer for viewing the generated reports in its
proprietary format or in the proprietary XML format produced by the internal XML
exporter. It is a Swing-based component. Other Java applications can easily integrate this
component without having to export the documents into more popular formats in order to
be viewed or printed. The net.sf.jasperreports.view.JRViewer class represents
this visual component. It can be customized to respond to a particular application’s needs
by subclassing it. For example, you could add or remove buttons from the existing
toolbar.
This is illustrated in the supplied /demo/samples/webapp sample, where the
JRViewerPlus class adds a new button to the existing toolbar of this report viewer
component. More details about how to extend the viewer component are provided in the
“Customizing Viewers” section on page 276.
JasperReports also comes with a simple Swing application that uses the visual
component for viewing the reports. This application helps view reports stored on disk in
the JasperReports *.jrprint proprietary format or in the JRPXML format produced by
the default XML exporter.
This simple Java Swing application is implemented in the
net.sf.jasperreports.view.JasperViewer class. It is used in almost all the
provided samples for viewing the generated reports.
To view a sample report if you have the Ant build tool installed on your system, go to the
desired sample directory and launch the following from the command line:
>ant view

or
>ant viewXML

You should see the window shown in Figure 4-1.

PAGE 25

THE JASPERREPORTS ULTIMATE GUIDE

Figure 4-1. Report viewer

Note
The viewer application implemented in the net.sf.jasperreports.view.JasperViewer
class should be considered a demo application that shows how the
net.sf.jasperreports.view.JRViewer component can be used in Swing applications to display
reports.
If you use it directly in your application by calling the public and static viewReport() methods it exposes,
when you close the report viewer frame, the application will unexpectedly terminate. This is because the
JasperViewer class makes a call to System.exit(0). A workaround is to subclass it and remove the
java.awt.event.WindowListener it has registered by default.

PAGE 26

THE JASPERREPORTS ULTIMATE GUIDE

PRINTING REPORTS
The main objective of the JasperReports library is to create ready-to-print documents.
Most reports that are generated by applications end up (or are supposed to end up) on
paper.
The printing functionality built into JasperReports at this time reflects the evolution of
printing capabilities within the Java platform.
JDK 1.2 introduced a new API called the Java 2 Printing API to allow Java applications
to render all Java 2D graphics on any platform even though the host and printer
capabilities are over matched by Java 2D. This requirement meant that the Printing API
in some situations would have had to rasterize Java 2D graphics on the host computer.
The SDK 1.2 Printing API primarily supplies the “imaging” portion of the print
subsystem and allows applications to format pages and draw their contents; however,
printer discovery is not supported by the SDK 1.2 Printing API. An application can
obtain information about the current printer and print to it by using the Printing API. The
printing dialog supplied by the Printing API also allows a user to change the current
printer, but the application cannot do this automatically.
Starting with JDK 1.4, a new Java print API called the Java Print Service API was
introduced to allow applications to print on all Java platforms (including platforms
requiring a small footprint, such as a J2ME profile) and still support the existing Java 2
Printing API. The Java Print Service API includes an extensible print attribute set based
on the standard attributes specified in the Internet Printing Protocol (IPP) 1.1 from the
Internet Engineering Task Force (IETF). With these attributes, client and server
applications can discover and select printers that have the capabilities specified by the
attributes.
You can print the documents generated by the JasperReports library using the
net.sf.jasperreports.engine.JasperPrintManager class, which is a facade class
that relies on the former Java 2 Printing API. Of course, documents can also be printed
after they are exported to other formats such as HTML or PDF. However, here we will
explain how to use the specialized manager class mentioned to print documents that are
stored or transferred in the JasperReports proprietary format
(net.sf.jasperreports.engine.JasperPrint objects).
Among the various methods that the
net.sf.jasperreports.engine.JasperPrintManager class exposes, some allow

printing a whole document, a single page, or a page range, with and without displaying
the print dialog.
Here’s how you can print an entire document without displaying the standard print
dialog:
JasperPrintManager.printReport(myReport, false);

PAGE 27

THE JASPERREPORTS ULTIMATE GUIDE

Here’s how to print all the pages from 5 to 11 of your document, after having displayed
the standard print dialog:
JasperPrintManager.printPages(myReport, 4, 10, true);

Making use of the much more flexible Java Print Service API introduced with JDK 1.4
requires a special exporter implementation. This implementation uses this new API to
allow applications to print JasperReports documents to printing services searched for
using attributes such as the network printer name and/or page size.
This is the net.sf.jasperreports.engine.export.JRPrintServiceExporter
class. More details about using it can be found in the “Java Print Service Exporter”
section on page 246.
An exporter implementation is well suited for sending documents to the printer through
the Java Print Service API, because in some ways printing is similar to document
exporting; both printing and exporting store generated reports in some other format
(paper).

EXPORTING REPORTS
In some application environments, it is useful to transform the JasperReports–generated
documents from the proprietary format into other, more popular formats like PDF,
HTML, RTF, or XLS. This way, users can view those reports without having to install
special viewers on their systems, which is especially important in the case of documents
sent over a network.
There is a facade class in JasperReports for this type of functionality:
net.sf.jasperreports.engine.JasperExportManager; it can be used to obtain
PDF, HTML, or XML content for the documents produced by the report-filling process.
Exporting means taking a net.sf.jasperreports.engine.JasperPrint object,
which represents a JasperReports document, and transforming it into a different format.
The main reason to export reports into other formats is to allow more people to view
those reports. HTML reports can be viewed by anybody these days, since at least one
browser is available on any system. Viewing JasperReports documents in their
proprietary form would require the installation of special software on the target platform
(at least a Java applet, if not more).
With time, more and more output formats will be supported by the JasperReports library.
For the moment, the various exporter implementations shipped with the library produce
only PDF, HTML, RTF, XLS, ODT, CSV, and XML output. These implementations are
found in the net.sf.jasperreports.engine.export package.
The JasperExportManager class offers easy access for only the PDF, HTML, and
XML implementations, as these have historically been the most common formats or
required the least export configuration.

PAGE 28

THE JASPERREPORTS ULTIMATE GUIDE

Here’s how you can export your report to HTML format using the facade export
manager class:
JasperExportManager.exportReportToHtmlFile(myReport);

To avoid excessive utility methods, this class was originally written such that the default
settings only offer easy access to the most common export formats. When new exporters
were added to the library, the export manager class was not extended, and users were
encouraged to use the exporter classes directly. Only by doing that could they fully
customize the behavior of that particular exporter using specific exporter parameters.
The chapter “Report Exporters” on page 235 explains in detail how to use each exporter
implementation currently shipped with the JasperReports library.
Note To export reports into other formats not supported by JasperReports, you must
implement a special interface called net.sf.jasperreports.engine.JRExporter or
extend the corresponding net.sf.jasperreports.engine.JRAbstractExporter
class.

PAGE 29

LARGE FILE SUPPORT
When filling report templates with data, the engine takes a JasperReport object along
with the supplied parameters and data source and generates an in-memory JasperPrint
object. If very large datasets are used for report filling, the size of the resulting
JasperPrint object could also be very large and might cause the JVM to run out of
memory.
To increase the memory available for the Java application, first use the -Xmx option
when launching the JVM, since the default value for this parameter is fairly small.
However, if you do this with large datasets (for example, containing tens of thousands or
more records and resulting in documents that have thousands or more pages), the JVM
may run out of memory.
Recent versions of JasperReports offer a simple solution to the problem by introducing
the report virtualizer. The virtualizer is a simple interface
(net.sf.jasperreports.engine.JRVirtualizer) that enables the reporting engine
to optimize memory consumption during report filling by removing parts of the
JasperPrint object from memory and storing them on disk or in other temporary
locations. If a report virtualizer is used during filling, the engine keeps only a limited
number of pages from the generated JasperPrint object at a time and serializes all the
other pages to a temporary storage location, usually the file system.
Using a report virtualizer is very simple. You supply an instance of the
net.sf.jasperreports.engine.JRVirtualizer interface as the value for the builtin REPORT_VIRTUALIZER parameter when filling the report.
In virtualized form, a generated JasperPrint document still behaves normally and can
be subject to exporting, printing, or viewing processes, and the impact on memory
consumption is minimal even when dealing with very large documents.
When produced using a virtualizer (which itself performs partial document serialization
into temporary files), once completed, a JasperPrint document can itself be serialized
normally without any loss of information. During the serialization of a virtualized
JasperPrint object, the program puts back together all the pieces and a single
serialized file is produced. However, because this single file is probably very large,
simple deserialization would not make sense (in fact, it wouldn’t be possible, as the JVM
would run out of memory, which is the reason for using virtualization in the first place).
So in order to reload into memory a virtualized document that was serialized to a
PAGE 30

THE JASPERREPORTS ULTIMATE GUIDE

permanent storage facility, a report virtualizer is needed. This would be set using a local
thread variable by calling the following:
JRVirtualizationHelper.setThreadVirtualizer(JRVirtualizer
virtualizer)

For details about how report virtualization can be used for generating large reports,
check the supplied /demo/samples/virtualizer sample.

FILE VIRTUALIZER
The library ships with a ready-to-use implementation of this interface called
net.sf.jasperreports.engine.fill.JRFileVirtualizer, which stores document
pages on disk during the filling process to free up memory. Once a JasperPrint object
is produced using a report virtualizer, it can be exported to other formats or viewed
directly using the library’s built-in viewer component, even though this document is not
fully loaded at any one time. The virtualizer ensures that pages are deserialized and
loaded from their temporary storage location as needed during exporting or display.
A single JRFileVirtualizer instance can be shared across multiple report-filling
processes so that the number of document pages kept in-memory at any one time will be
limited by the virtualizer maxSize property, regardless of the number of reports that are
generated simultaneously.
Because it works with temporary files on disk, the file virtualizer has a built-in
mechanism to remove those files after they are no longer needed (that is, after the
generated document or the virtualizer itself have been disposed of by the JVM). The
cleanup() method exposed by this virtualizer implementation can be also called
manually so that the temporary files are removed from disk right away instead of after
the finalization of the entities involved.
To ensure that no virtualization files are left over on disk by the application that uses the
file virtualizer, all these temporary files are registered with the JVM so that they are
deleted automatically when the JVM exits normally.
But using File.deleteOnExit() will accumulate JVM process memory on some
virtual machine implementations (see
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4513817); you should
avoid using this feature in long-running applications by turning it off using the
net.sf.jasperreports.virtualizer.files.delete.on.exit configuration
property.

SWAP FILE VIRTUALIZER
On some platforms, working with a large number of files in a single folder, or even the
file manipulating processes themselves, may have a significant impact on performance or
PAGE 31

THE JASPERREPORTS ULTIMATE GUIDE

pose additional problems. This makes the use of the JRFileVirtualizer
implementation less effective.
Fortunately, there is another implementation of a file-based report virtualizer that uses a
single swap file and can also be shared among multiple report-filling processes. Instead
of having one temporary file per virtualized page, we create a single file into which all
virtualized pages are stored to and then retrieved from.
This swap file virtualizer implementation is represented by the
net.sf.jasperreports.engine.fill.JRSwapFileVirtualizer class that is now

part of the JasperReports library core functionality, and works in combination with a
net.sf.jasperreports.engine.util.JRSwapFile instance representing the target
swap file.
The JRSwapFile instance has to be created and configured prior to being passed to the
swap virtualizer. You can create such an instance by specifying the target directory
where the swap file will be created, the size of the blocks allocated by the swap file, and
the minimum number of blocks by which the swap file will grow when its current size
becomes insufficient.
The net.sf.jasperreports.engine.util.JRConcurrentSwapFile class
represents an enhanced implementation of the JRSwapFile that only works with JRE
version 1.4 or later, because it uses a java.nio.channels.FileChannel to perform
concurrent I/O on the swap file.

IN-MEMORY GZIP VIRTUALIZER
The net.sf.jasperreports.engine.fill.JRGzipVirtualizer is a convenient
report virtualizer implementation that does not rely on the file system to temporarily
store unused/virtualized document pages during the report filling. Rather, it optimizes
memory consumption by compressing those pages in-memory using a GZIP algorithm.
Tests indicate that memory consumption during large report-generating processes is
reduced up to a factor of ten when the in-memory GZIP report virtualizer is used.

PAGE 32

API OVERVIEW
Usually you will work only with a few JasperReports library classes and won’t have to
get to know the entire API.
This section addresses the classes and interfaces that are significant when using the
library, and shows you how to use them in applications that require reporting
functionality (see Figure 6-1).
JasperPrintManager

JasperFillManager

print

Screen
Printer

JRXML

parse

JasperDesign

JRXmlLoader

compile

JasperReport

fill

PDF

JasperPrint
export

JRCompiler

HTML
XML

JasperCompileManager

JasperExportManager

Figure 6-1. JasperReports API overview

NET.SF.JASPERREPORTS.ENGINE.DESIGN.JASPERDESIGN
Instances of this class are the raw material that the JasperReports library uses to generate
reports. Such instances are usually obtained by parsing the JRXML report template files
using the library’s internal XML-parsing utility classes. But they can also be
independently generated by the application that uses JasperReports through API calls if
working with JRXML files is not an option. Third-party GUI design tools use the
JasperReports API to create these report template objects. Among the supplied samples
that come with the project source files, there is one inside
/demo/samples/noxmldesign that you can check to see how to dynamically create a
JasperDesign object without editing a JRXML report design file.
All instances of the JasperDesign class are subject to compilation before being used
for filling and report generation. This is why they are considered the raw material for the
library.

PAGE 33

THE JASPERREPORTS ULTIMATE GUIDE

NET.SF.JASPERREPORTS.ENGINE.JASPERREPORT
Instances of this class represent compiled report template objects. They are obtained only
through the JasperReports report compilation process and are ready to use for filling with
data and report generation.
Through compilation, along with various consistency checks and rearrangements of the
report elements for more rapid performance in the application, the library creates an onthe-fly class file (or a script, depending on the type of the report compiler used)
containing all the report expressions (such as report variables expressions, text field and
image expressions, and group expressions). This class or script is used to evaluate report
expressions during the report-filling process at runtime.

NET.SF.JASPERREPORTS.ENGINE.JASPERCOMPILEMANAGER
This is the class that exposes all the library’s report compilation functionality. It has
various methods that allow the users to compile JRXML report templates found in files
on disk or that come from input streams. It also lets you compile in-memory report
templates by directly passing a
net.sf.jasperreports.engine.design.JasperDesign object and receiving the
corresponding net.sf.jasperreports.engine.JasperReport object.
Other utility methods include report template verification and JRXML report template
generation for in-memory constructed
net.sf.jasperreports.engine.design.JasperDesign class instances. These
instances are especially useful in GUI tools that simplify report design work.

NET.SF.JASPERREPORTS.ENGINE.JASPERPRINT
After a compiled report template is filled with data, the resulting document comes in the
form of a net.sf.jasperreports.engine.JasperPrint instance. Such an object
can be viewed directly using the built-in JasperReports report viewer, or can be
serialized for disk storage and later use or sending over the network.
The instances of this class are the output of the report-filling process of the
JasperReports library, and represent its proprietary format for storing full-featured, pageoriented documents. You can transform them into other more popular formats (such as
PDF, HTML, RTF, XLS, ODT, CSV, or XML) by using the library’s export
functionality.

NET.SF.JASPERREPORTS.ENGINE.JRDATASOURCE
JasperReports is very flexible as to the source of the report data. It lets people use any
kind of data source they want, as long as they can provide an appropriate implementation
of this interface.

PAGE 34

THE JASPERREPORTS ULTIMATE GUIDE

Normally, every time a report is filled, an instance of this interface is supplied or created
behind the scenes by the reporting engine.

NET.SF.JASPERREPORTS.ENGINE.JRRESULTSETDATASOURCE
This is a default implementation of the
net.sf.jasperreports.engine.JRDataSource interface. Since most reports are

generated using data from a relational database, JasperReports includes by default this
implementation that wraps a java.sql.ResultSet object.
This class can be instantiated intentionally to wrap already loaded result sets before
passing them to the report-filling routines, but it is also used by the reporting engine to
wrap the data retrieved from the database after having executed the report query (if
present) through JDBC.

NET.SF.JASPERREPORTS.ENGINE.DATA.JRBEANARRAYDATASOURCE AND
NET.SF.JASPERREPORTS.ENGINE.DATA.JRBEANCOLLECTIONDATASOURCE
It is now common to access application data through object persistence layers like EJB,
Hibernate, or JDO. Such applications may need to generate reports using data they
already have available as arrays or collections of in-memory JavaBean objects.
JasperReports ships with two JavaBean-compliant data source implementations that can
wrap either an array or a collection of JavaBean objects.
This can be seen in the supplied /demo/samples/datasource sample, where instances
of a custom JavaBean class are used to fill a report with data.

NET.SF.JASPERREPORTS.ENGINE.DATA.JRXMLDATASOURCE
If application data resides inside XML files, and you need this data to generate reports,
the built-in XPath-based implementations of the JRDataSource interface are useful.
With the help of an XPath query, the XML data can take a tabular form and be fed into
the report-filling process to generate documents.
The /demo/samples/xmldatasource sample in the distribution package shows how
this special data source implementation can be used with XML data.

NET.SF.JASPERREPORTS.ENGINE.JREMPTYDATASOURCE
The simplest implementation of the net.sf.jasperreports.engine.JRDataSource
interface, this class can be used in reports that do not display data from the supplied data
source, but rather from parameters, and when only the number of virtual rows in the data
source is important.
Many of the provided samples found in the /demo/samples directory of the project’s
distribution (such as fonts, images, shapes, and unicode) use an instance of this class
PAGE 35

THE JASPERREPORTS ULTIMATE GUIDE

when filling reports to simulate a data source with one record in it, but with all the fields
in this single record being null.

NET.SF.JASPERREPORTS.ENGINE.JASPERFILLMANAGER
This class is the facade to the report-filling functionality of the JasperReports library. It
exposes a variety of methods that receive a report template in the form of an object, file,
or input stream, and also produces a document in various output forms (object, file, or
output stream).
Along with the report template, the report-filling engine must also receive data from the
data source, as well as the values for the report parameters, to generate the documents.
Parameter values are always supplied in a java.util.Map object, in which the keys are
the report parameter names.
The data source can be supplied in two different forms, depending on the situation.
Normally, it is supplied as a net.sf.jasperreports.engine.JRDataSource object,
as just mentioned.
However, since most reports are filled with data from relational databases, JasperReports
has a built-in default behavior that lets people specify an SQL query in the report
template itself. This SQL query is executed to retrieve the data for filling the report at
runtime.
In such cases, the only thing JasperReports needs is a java.sql.Connection object,
instead of the usual data source object. It needs this connection object to connect to the
relational database management system through JDBC and execute the report query.
It automatically creates a
net.sf.jasperreports.engine.JRResultSetDataSource behind the scenes to
wrap the java.sql.ResultSet object returned after the execution of the query and

passes it to the normal report-filling process.

NET.SF.JASPERREPORTS.ENGINE.JRABSTRACTSCRIPLET
Scriptlets are a very powerful feature of the JasperReports library. They allow users to
write custom code to be executed by the reporting engine during the report-filling
process. This user code can manipulate report data and gets executed at well-defined
moments such as page, column, or group breaks.

NET.SF.JASPERREPORTS.ENGINE.JRDEFAULTSCRIPTLET
This is a convenient subclass of the
net.sf.jasperreports.engine.JRAbstractScriptlet class. You will usually

subclass this when working with scriptlets so that they don’t have to implement all the
abstract methods declared in the abstract class.
PAGE 36

THE JASPERREPORTS ULTIMATE GUIDE

NET.SF.JASPERREPORTS.ENGINE.JASPERPRINTMANAGER
After having filled a report, you have the option of viewing it, exporting it to a different
format, or (most commonly) printing it.
In JasperReports, you can print reports using this manager class, which is a facade to the
printing functionality exposed by the library. This class contains various methods that
can send entire documents or portions of them to the printer. It also allows you to choose
whether to display the print dialog. You can display the content of a page from a
JasperReports document by generating a java.awt.Image object for it using this
manager class.

NET.SF.JASPERREPORTS.ENGINE.JASPEREXPORTMANAGER
As already mentioned, JasperReports can transform generated documents from its
proprietary format into more popular documents formats such as PDF, HTML, or XML.
Over time, this part of the JasperReports functionality has been extended to support other
formats, including RTF, XSL, and CSV.
This manager class has various methods that can process data that comes from different
sources and goes to different destinations (files, input and output streams, etc.).

NET.SF.JASPERREPORTS.ENGINE.JASPERRUNMANAGER
Sometimes it is useful to produce documents only in a popular format such as PDF or
HTML, without having to store on disk the serialized, intermediate
net.sf.jasperreports.engine.JasperPrint object produced by the report-filling
process.
This can be achieved using this manager class, which immediately exports the document
produced by the report-filling process into the desired output format.
The use of this manager class is shown and can be tested in the supplied
/demo/samples/ webapp sample, where PDF and HTML content is produced on the
fly.

NET.SF.JASPERREPORTS.VIEW.JRVIEWER
This class is different from the rest of the classes listed previously in that it is more like a
pluggable visual component than a utility class. It can be used in Swing-based
applications to view the reports generated by the JasperReports library.
This visual component is not meant to satisfy everybody. It was included like a demo
component to show how the core printing functionality can be used to display the reports
in Swing-based applications.
The preferred way to adapt this component to a particular application is by subclassing it.
The “Customizing Viewers” section on page 276 gives more details about this.
PAGE 37

THE JASPERREPORTS ULTIMATE GUIDE

NET.SF.JASPERREPORTS.VIEW.JASPERVIEWER
This class also serves a didactic purpose. It uses the
net.sf.jasperreports.view.JRViewer component to display reports. It represents a
simple Java Swing application that can load and display reports. It is used in almost all of
the supplied samples to display the generated documents.

NET.SF.JASPERREPORTS.VIEW.JASPERDESIGNVIEWER
Usually, an application that uses the JasperReports library for reporting purposes will
never use this class. This class can be used at design time to preview the report
templates. It was included in the main library as a development tool in order to make up
for the missing visual designer.
This class is also used in all the samples to preview the report designs, either in raw
JRXML form or the compiled form.

NET.SF.JASPERREPORTS.ENGINE.UTIL.JRLOADER
Many JasperReports processes, like report compilation, report filling, and exporting,
often work with serialized objects. Sometimes it is useful to manually load those
serialized objects before submitting them to the desired JasperReport process.
The net.sf.jasperreports.engine.util.JRLoader class is a utility class that
helps load serialized objects found in various locations such as files, URLs, and input
streams.
The most interesting method exposed by this class is
loadObjectFromLocation(String). When calling this method to load an object from
the supplied location, the program first tries to interpret the location as a valid URL. If
this fails, then the program assumes that the supplied location is the name of a file on
disk and tries to read from it. If no file is found at that location, it will try to locate a
resource through the classpath that would correspond to the location. Only after this third
try fails is an exception thrown.

NET.SF.JASPERREPORTS.ENGINE.UTIL.JRSAVER
This utility class can be used when serializable objects must be saved on disk or sent
over the network through an output stream.

NET.SF.JASPERREPORTS.ENGINE.XML.JRXMLLOADER
Parsing a JRXML file into a JasperDesign object can be done using one of the
methods published by this class. Applications might need to do this in cases where report
templates kept in their source form (JRXML) must be modified at runtime based on
some user input and then compiled on the fly for filling with data.
PAGE 38

THE JASPERREPORTS ULTIMATE GUIDE

NET.SF.JASPERREPORTS.ENGINE.XML.JRPRINTXMLLOADER
Generated documents can be stored in XML format if they are exported using the
net.sf.jasperreports.engine.export.JRXmlExporter. After they’re exported,
you can parse them back into net.sf.jasperreports.engine.JasperPrint objects
by using this JRPrintXmlLoader.

PAGE 39

REPORT TEMPLATE STRUCTURE
Generally speaking, a report template contains all the information about the structure and
the aspects of the documents that will be generated when the data is provided. This
information determines the position and content of various text or graphic elements that
will appear in the document, their appearance, the custom calculations, the data grouping
and data manipulation that should be performed when the documents are generated, and
so on.
Creating report templates was discussed in “Filling Report Templates” on page 19. This
chapter will delve into the structure of a report template and demonstrate how each
component and property can be used to achieve specific functionality.

JRXML
JRXML is the name we use when referring to XML files that represent the definition of a
JasperReports template and that comply with the mentioned XSD structure.
When working with JRXML report templates, JasperReports uses its own internal XSD
files to validate the XML content it receives for processing. If the XML validation
passes, it means that the supplied report design corresponds to the JasperReportsrequired XML structure and syntax, and the engine is able to generate the compiled
version of the report design.
Valid JRXML report templates always point to the JasperReports internal XSD files for
validation. If the XSD reference is not specified, report compilation will fail abruptly.
This should not be a big problem since the XSD reference is always the same and can
simply be copied from previous report templates. To start with, you can copy it from the
supplied samples.

XSD REFERENCE
As already mentioned, the engine recognizes only the XSD references that point to its
internal XSD files. You cannot make a copy of the XSD files found among the library
source files and point to that copy in your JRXML report templates. To do that, you must
alter the code of some of the library classes, including the
net.sf.jasperreports.engine.xml.JRXmlDigester class.

PAGE 40

THE JASPERREPORTS ULTIMATE GUIDE

If you encounter problems, such as the engine not finding its own internal XSD files due
to some resource-loading problems, make sure you have eliminated every possible cause
before deciding to use external XSD files. You will probably not encounter such a
problem since the resource-loading mechanism of the library has improved with time.
The root element of a JRXML report template is . This is what a
typical JasperReports JRXML report template file looks like and how the XSD is
referenced:


...


The first ellipsis (...) represents the report-design properties and settings, and the
second ellipsis represents the various suppressed report-design elements, such as report
parameters, fields, variables, groups, report sections, and so on. Examples of these
follow in later chapters of this book.

JRXML ENCODING
When creating JRXML report templates in different languages, pay special attention to
the encoding attribute that can be used in the header of the XML file. By default, if no
value is specified for this attribute, the XML parser uses UTF-8 as the encoding for the
content of the XML file.
This is important because the report design often contains localized static texts, which
are introduced when manually editing the JRXML file.
For most Western European languages, the ISO-8859-1 encoding, also known as
LATIN1, is sufficient. For example, it includes the special French characters é, â, è, and
ç, and can be specified using the encoding attribute shown in the following example:



...


To find out the encoding type to specify when editing XML files in a particular
language, check the XML documentation.

REPORT TEMPLATE PROPERTIES
You have already seen that  is the root element of a JRXML report
design. This section will show in detail the properties of a report-design object and the
JRXML attributes that correspond to them.
Listing 7-1 gives the JRXML syntax for the report template properties.
Listing 7-1. JRXML Syntax



REPORT NAME
Every report design needs a name. It's name is important because the library uses it when
generating files, especially when the default behavior is preferred for compiling, filling,
or exporting the report.
The name of the report is specified using the name attribute of the 
element, and its inclusion is mandatory. Spaces are not allowed in the report name—it
must be a single word.

LANGUAGE
Report expressions are usually written using the Java language. However, you can use
other languages as long as a report compiler is available to help evaluate these
expressions at report-filling time.
The default value for the language property is java, meaning that the Java language is
used for writing expressions, and that a report compiler capable of generating and
compiling a Java class on the fly is used for producing the bytecode needed for
expression evaluation at runtime.
Report compilers reference this property to see whether they can compile the supplied
report template or whether a different report compiler should be used, depending on the
actual scripting language.
The distribution includes a sample inside the /demo/samples/groovy folder, which
demonstrates how other scripting languages can be used in JasperReports templates.

COLUMN COUNT
JasperReports lets users create reports with more than one column on each page.
Multicolumn report templates also have an associated column-filling order specified by
the next attribute in this section, printOrder. Figure 3-1 on page 22 shows an example
of what multicolumn report templates look like.
By default, the reporting engine creates reports with one column on each page.

PRINT ORDER
For reports having more that one column, it is important to specify the order in which the
columns will be filled. You can do this using the printOrder attribute of the
 element.
PAGE 43

THE JASPERREPORTS ULTIMATE GUIDE

There are two possible situations:
 Vertical filling: Columns are filled from top to bottom and then left to right
(printOrder="Vertical").
 Horizontal filling: Columns are filled from left to right and then top to bottom
(printOrder="Horizontal").
The default print order is printOrder="Vertical".

PAGE SIZE
There are two attributes at this level to specify the page size of the document that will be
generated: pageWidth and pageHeight. Like all the other JasperReports attributes that
represent element dimensions and position, these are specified in pixels. JasperReports
uses the default Java resolution of 72 dots per inch (DPI). This means that
pageWidth="595" will be about 8.26 inches, which is roughly the width of an A4 sheet
of paper.
The default page size corresponds to an A4 sheet of paper:
pageWith="595" pageHeight="842"

PAGE ORIENTATION
The orientation attribute determines whether the documents use the Portrait or the
Landscape format. JasperReports requires you to adapt the page width and the page
height when switching from Portrait documents to Landscape, and vice versa. For
example, assume that you want to create an A4 report using the Portrait layout.
An A4 report has approximately this size:
pageWidth="595" pageHeight="842" orientation="Portrait"

If you decide to use the Landscape layout for your A4 document, you must be sure to
modify the page width and page height accordingly, as follows:
pageWidth="842" pageHeight="595" orientation="Landscape"

This is because JasperReports has to know exactly the absolute width and height of the
pages it will draw on, and does not necessarily consider the value supplied in the
orientation attribute, at least not at report-filling time.
This orientation attribute is useful only at report-printing time to inform the printer
about the page orientation, and in some special exporters. The default page orientation is
"Portrait".

PAGE 44

THE JASPERREPORTS ULTIMATE GUIDE

PAGE MARGINS
Once the page size is decided, you can specify what margins the reporting engine should
preserve when generating the reports. Four attributes control this: topMargin,
leftMargin, bottomMargin, and rightMargin (see Figure 3-1 on page 22).
The default margin for the top and bottom of the page is 20 pixels. The default margin
for the right and left margins is 30 pixels.

COLUMN SIZE AND SPACING
Reports may have more that one column, as shown in the preceding discussion of the
columnCount attribute. However, the reporting engine has to know how large a column
can be and how much space should be allowed between columns. Two attributes control
this: columnWidth and columnSpacing.
Also, when you compile a report JasperReports checks whether the width of the overall
columns and the space between them exceed the specified page width and page margins.
Since there is only one column by default, the default column spacing is 0 pixels and the
default column width is 555 pixels (the default page width minus the default left and
right margins).

EMPTY DATA SOURCE BEHAVIOR
The data source for a report might not contain any records. In this case, it is not clear
what the output should be. Some may expect to see a blank document and others may
want some of the report sections to be displayed anyway.
The whenNoDataType attribute lets you decide how the generated document should look
when there is no data in the data source supplied to it.
The possible values of this attribute are as follows:
 Empty document: The generated document will have no pages in it. Viewers might
throw an error when trying to load such documents
(whenNoDataType="NoPages").
 Blank page: The generated document will contain a single blank page
(whenNoDataType="BlankPage").
 All sections displayed: All the report sections except the detail section will appear
in the generated document (whenNoDataType="AllSectionsNoDetail").
The default value for this attribute is whenNoDataType="NoPages".

PAGE 45

THE JASPERREPORTS ULTIMATE GUIDE

TITLE AND SUMMARY SECTION PLACEMENT
To display the title or summary section on a separate page, set one or both of the
following attributes to true:
isTitleNewPage
isSummaryNewPage.

Both of these Boolean attributes are set to false by default.
When the summary section stretches to a new page, or starts on a new page altogether, it
is not accompanied by the page header and page footer. In order to force the page header
and page footer to reappear on summary trailing pages, set the
isSummaryWithPageHeaderAndFooter to true; it is set to false by default.

Note
Even if you choose to display the summary section in the remaining space of the last page, a new page
will automatically start if the report has more than one column and the second column has already started on the
last page.

COLUMN FOOTER PLACEMENT
The isFloatColumnFooter Boolean property lets users customize the behavior of the
column footer section. By default, this section is rendered at the bottom of the page, just
above the page footer. In certain cases, it is useful to render it higher on the page, just
below the last detail or group footer on that particular column. To do this, set the
isFloatColumnFooter property to true.

SCRIPTLET CLASS
The scriptletClass attribute lets you specify the name of the scriptlet class designed
for the current report. You will learn more about scriptlets in “Scriptlets” on page 230,
where you'll see that there can be multiple scriptlet instances associated with a report.
This attribute here is just a convenient way to specify the scriptlet class in case there is
only one scriptlet associated with the report.
This attribute is used by the engine only if no value is supplied for the built-in
JRParameter.REPORT_SCRIPTLET parameter. If neither the attribute nor the parameter
is used, and no other scriptlet is specified for the report using named scriptlet tags the
reporting engine uses a single
net.sf.jasperreports.engine.JRDefaultScriptlet instance as the report
scriptlet.

PAGE 46

THE JASPERREPORTS ULTIMATE GUIDE

RESOURCE BUNDLE
To generate reports in different languages from the same report template, associate a
resource bundle with the template and make sure that the locale-specific resources inside
report expressions are retrieved based on the $R{} syntax (explained in “Reporting Data”
on page 56).
There are two ways to associate the java.util.ResourceBundle object with the
report template.
The first is a static association made by setting the resourceBundle property of the
report template object to the base name of the target resource bundle.
A dynamic association can be made by supplying a java.util.ResourceBundle
object as the value for the REPORT_RESOURCE_BUNDLE parameter at report-filling time.
See “Internationalization” on page 234 for more details.

MISSING RESOURCES BEHAVIOR
The whenResourceMissingType property allows users to choose the desired behavior
of the engine when it deals with missing locale-specific resources in the supplied
resource bundle. There are four different values that can be used to deal with missing
resources:
 Null: The null value is used (whenResourceMissingType="Null").
 Empty: An empty string is used (whenResourceMissingType="Empty").
 Key: The key is used (whenResourceMissingType="Empty").
 Error: An exception is raised in case a locale-specific resource is not found in the
supplied resource bundle for the given key and locale
(whenResourceMissingType="Error").

PAGINATION
When the isIgnorePagination property is set to true, the report-filling engine will
completely ignore page break–related settings inside the report template and generate the
document on a single, very long page. The value of this property can be overridden at
runtime using the optional, built-in IS_IGNORE_PAGINATION parameter.

FORMATTING NUMBERS, DATES, AND TIMES
The formatFactoryClass attribute lets you specify the name of the factory class
implementing the net.sf.jasperreports.engine.util.FormatFactory interface,
which should be instantiated by the engine in order to produce java.text.DateFormat
and java.text.NumberFormat objects to use for date and number formatting in the
current report.

PAGE 47

THE JASPERREPORTS ULTIMATE GUIDE

This attribute specifying the factory class name is used only if no value is supplied for
the built-in JRParameter.REPORT_FORMAT_FACTORY parameter.
If neither of the attribute nor the parameter is used, the engine will eventually instantiate
the net.sf.jasperreports.engine.util.DefaultFormatFactory implementation
of the factory interface, which produces java.text.SimpleDateFormat and
java.text.DecimalFormat objects for date and number formatting.
You need to use this attribute or the built-in JRParameter.REPORT_FORMAT_FACTORY
parameter only if the report relies on custom date and number formatters.

CUSTOM PROPERTIES
Sometimes it is useful to put some information into the report template itself. This
information can be used by the parent application at runtime after loading the report
template, or it can be used by the UI report-design tools to store designer-specific
information, like whether to display the rules, the size of the snap grid, and so on.
Some of the properties can be transferred onto the generated document and can be used
by exporter to tailor their behavior. These are also know as exporter hints and more
details about them can be found in ”Report Exporters” on page 235.
The report templates can store application or user-defined properties in the form of
named values that can be archived by using any number or  tags inside the
report template.
Listing 7-2 gives the JRXML syntax for the report custom properties.
Listing 7-2. JRXML Syntax



It is recommended that property names rely on some namespace policy, just as Java
application packages do, to ensure that no naming conflict arises when several
applications store information in the same report template.
Here is how a named value can be put inside the report template:



At runtime, this application-defined data can be retrieved from the report template using
the API, as follows:

PAGE 48

THE JASPERREPORTS ULTIMATE GUIDE
JasperReport jasperReport =
(JasperReport)JRLoader.loadObjectFromLocation(
"C:/MyApp/src/reports/MyReport.jasper");
String author =
jasperReport.getProperty("com.mycompany.report.author");
String desc =
jasperReport.getProperty("com.mycompany.report.description");

IMPORTING PACKAGES
Using the Java language for writing the report expressions gives great flexibility to the
library because report designers can leverage existing code inside JasperReports’ parent
Java applications.
When using Java, all the report expressions are put into a Java source file that is created
on the fly at report-compilation time. This source file is compiled to bytecode by the
report compiler and used for expression evaluation at report-filling time. Being a normal
Java source file, it can have import statements at the top to simplify how classes are
referenced inside the source code. When entire packages are imported, report expressions
can reference application classes by name rather than full class name (including the
package), resulting in shorter and simpler report expressions.
For importing entire packages or single classes, several  tags can be used
inside the report template.
Listing 7-3 gives the JRXML syntax for importing packages.
Listing 7-3. JRXML Syntax



The following example shows how to import an entire package and a single class:



A report template can contain any number of import tags.

STYLES
A report style is a collection of style settings declared at the report level. These settings
can be reused throughout the entire report template when setting the style properties of
report elements.
PAGE 49

THE JASPERREPORTS ULTIMATE GUIDE

Listing 7-4 gives the JRXML syntax for the report style definitions.
Listing 7-4. JRXML Syntax





REPORT STYLE NAME
The name attribute of a 

In the preceding example, elements with this style will have red forecolor. But the
presence of the conditional style modifies the behavior, and when rendered on an even
row, the same elements will have blue forecolor.
An important aspect is the priority of styles. When applied, a conditional style will
override the properties of its parent style. In the preceding example, an even detail row
will inherit the fontName property from the parent style and overwrite the forecolor
property.
A style can contain more than one conditional style. In this case, all conditionals that
evaluate to true will be appended to the existing style (the second style will be
appended to the first, and so on). Here is a more elaborate example:


In this example, if the field amount is greater than 10,000, the second conditional style is
true, and the element displays in bold (it also has red color or blue color depending on
whether it is on an even or odd row). If the amount is greater than 20,000, then the last
two style conditions will be true and will be applied in order. They will override
isBold and add isItalic.
For amounts over 10,000, elements will be written in bold, and for amounts over 20,000,
elements will be written in italic (but not bold). Of course, all conditional styles will
inherit the font from the parent style.

PAGE 52

THE JASPERREPORTS ULTIMATE GUIDE

By default, the style condition expressions are evaluated during the report filling process
at the time that the style reference is used. The conditional expression evaluation will use
the current values of referenced variables and fields, regardless of the evaluationTime
attribute of the element that makes use of the style.
If the evaluation of the condition expression of the style needs to be delayed, just like the
value of the text field or the image element that uses the conditional style, the
net.sf.jasperreports.style.evaluation.time.enabled configuration property
should be set to true.

REFERENCING A REPORT STYLE
All report elements can reference a report style to inherit all or part of the style
properties. A report style declaration groups all the style-related properties supported
throughout the library, but an individual element inherits only those style properties that
apply to it. The others will be ignored.
See ”Report Elements” on page 114 for details about applying styles to report elements.

STYLE TEMPLATES
Report styles can also be defined in external style template files that are referenced by
report templates. This allows report designers to define in a single place a common look
for a set of reports.
A style template is an XML file that contains one or more style definitions. A template
can include references to other style template files, hence one can organize a style library
as a hierarchical set of style template files.
Style template files use by convention the *.jrtx extension, but this is not mandatory.
These files use a simple DTD schema, illustrated below:
Listing 7-5. JRXML Syntax




The  element is the root of a style template file. The