IReport Ultimate Guide

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 364 [warning: Documents this large are best viewed by clicking the View PDF Link!]

ULTIMATE GUIDE
Jaspersoft
iReport Designer
iReport Ultimate Guide
2
Copyright © 2013 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 0113-UGI50-6 of the iReport Ultimate Guide.
Table of Contents
3
TABLE OF CONTENTS
Chapter 1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.1 Features of iReport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.2 The iReport Community . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3 JasperReports Commercial License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.4 Code Used in This Book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Chapter 2 Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.1 Platform Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.2 Downloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.3 Development Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.4 Compiling iReport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.5 Installing iReport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.6 The Windows Installer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.7 Installing iReport on Mac OSX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.8 First iReport Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.9 Creating a JDBC Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
2.10 Creating Your First Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.10.1 Using the Sample Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.10.2 Using the Report Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Chapter 3 Basic Notions of JasperReports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.1 The Report Life Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2 JRXML Sources and Jasper Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.3 Data Sources and Print Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.4 Compatibility Between Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.5 Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.5.1 The Type of an Expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
3.5.2 Expression Operators and Object Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.5.3 Using an If-Else Construct in an Expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
4
Jaspersoft Style Guide and FrameMaker Template
3.6 Using Java as a Language for Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.7 Using Groovy as a Language for Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.8 Using JavaScript as a Language for Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.9 Using JasperReports Extensions in iReport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
3.10 A Simple Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Chapter 4 Report Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.1 Bands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.1.1 Report Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.1.2 Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.1.3 Advanced Report Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
4.2 Working with Bands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
4.2.1 Band Height . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
4.2.2 Print When Expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
4.2.3 Split Allowed and Split Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Chapter 5 Report Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
5.1 Working with Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
5.1.1 Formatting Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
5.1.2 Managing Elements with the Report Inspector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
5.1.3 Basic Element Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
5.1.4 Element Custom Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
5.1.5 Graphic Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
5.2 Working with Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
5.2.1 Padding and Borders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.2.2 Loading an Image from the Database (BLOB Field) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
5.2.3 Creating an Image Dynamically . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
5.3 Working with Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
5.3.1 Static Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
5.3.2 Textfields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
5.4 Other Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
5.4.1 Subreports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
5.4.2 Frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
5.4.3 Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
5.4.4 Crosstab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
5.4.5 Page/Column Break . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
5.5 Adding Custom Components and Generic Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
5.6 Anchors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
5.6.1 Hyperlink Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
5.6.2 Hyperlink Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
5.6.3 Hyperlink Tooltip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Chapter 6 Fields, Parameters, and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
6.1 Working with Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Table of Contents
5
6.1.1 Registration of the Fields from a SQL Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
6.1.2 Accessing the SQL Query Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
6.1.3 Registration of the Fields of a JavaBean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
6.1.4 Fields and Textfields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
6.2 Working with Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
6.2.1 Using Parameters in a Query . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
6.2.2 IN and NOTIN clause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
6.2.3 Built-in Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
6.2.4 Relative Dates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
6.2.5 Passing Parameters from a Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
6.3 Working with Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
6.4 Evaluating Elements During Report Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Chapter 7 Bands and Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
7.1 Modifying Bands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
7.2 Working with Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
7.3 Other Group Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Chapter 8 Fonts and Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
8.1 Working with Fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
8.2 Using TrueType Fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
8.3 Using the Font Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
8.4 Character Encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
8.5 Use of Unicode Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
8.6 Working with Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
8.7 Creating Style Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
8.8 Referencing Styles in External Property Sheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
Chapter 9 Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
9.1 Template Structure Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
9.2 Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
9.3 Column Header . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
9.4 Detail Band . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
9.5 Template Type and Other Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
9.6 Creating a New Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
9.7 Installing and Using the Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Chapter 10 Data Sources and Query Executers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
10.1 How a JasperReports Data Source Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
10.2 Understanding Data Sources and Connections in iReport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
10.3 Creating and Using JDBC Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
10.3.1 ClassNotFoundError . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
10.3.2 URL Not Correct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
10.3.3 Parameters Not Correct for the Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
10.3.4 Creating a JDBC Connection via the Services View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
6
Jaspersoft Style Guide and FrameMaker Template
10.4 Working with Your JDBC Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161
10.4.1 Fields Registration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
10.4.2 Sorting and Filtering Records . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
10.5 Understanding the JRDataSource Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
10.6 Data Source Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
10.6.1 Using JavaBeans Set Data Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
10.6.2 Fields of a JavaBean Set Data Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
10.6.3 Using XML Data Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
10.6.4 Registration of the Fields for an XML Data Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
10.6.5 XML Data Source and Subreports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
10.6.6 Using CSV Data Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
10.6.7 Registration of the Fields for a CSV Data Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
10.6.8 Using JREmptyDataSource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
10.6.9 Using HQL and Hibernate Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
10.6.10 Using a Hadoop Hive Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
10.6.11 How to Implement a New JRDataSource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
10.6.12 Using a Personalized JRDataSource with iReport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
10.7 Importing and Exporting Data Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
10.8 Creating Custom Languages and Query Executers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
10.8.1 Creating a Query Executer for a Custom Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
10.8.2 Creating a FieldsProvider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
Chapter 11 Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
11.1 Creating a Simple Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
11.2 Using Datasets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
11.3 Value Hyperlinks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
11.4 Properties of Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
11.5 Using Chart Themes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
11.5.1 Using the Chart Theme Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
11.5.2 Creating a JasperReports Extension for a Chart Theme . . . . . . . . . . . . . . . . . . . . . . . . . . 212
11.5.3 Using a Chart Theme in the Report Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
11.6 HTML5 Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Chapter 12 Flash Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
12.1 Viewing Flash Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
12.2 Using Maps Pro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
12.2.1 Creating Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
12.2.2 Determining Map Entity IDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
12.2.3 Specifying Map Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229
12.2.4 Specifying Map Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
12.2.5 Localizing Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
12.3 Using Charts Pro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
12.3.1 Creating Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
12.3.2 Specifying Chart Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
12.3.3 Defining Trend Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
Table of Contents
7
12.4 Using Widgets Pro . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
12.4.1 Widget Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
12.4.2 Creating Widgets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
12.4.3 Specifying Widget Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
12.5 Embedding Components in a Java Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
12.6 Localizing a Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
12.7 Component Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
Chapter 13 Lists, Tables, and Barcodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
13.1 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
13.1.1 Working with the List Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
13.1.2 Parameters and Variables in a List Element . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262
13.1.3 List Component Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
13.1.4 Print Order: Vertical and Horizontal Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
13.1.5 Other Uses of the List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
13.1.6 Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
13.2 Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
13.2.1 Creating a Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
13.2.2 Table Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
13.2.3 Editing the Table Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
13.2.4 Editing the Dataset Run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
13.2.5 Working with Columns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274
13.2.6 Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
13.3 Barcodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
13.3.1 Working with Barcodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
13.3.2 Barbecue Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
13.3.3 Barcode4J Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
13.3.4 Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Chapter 14 Subdatasets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
14.1 Creating a Subdataset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
14.2 Creating Dataset Runs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
14.3 Working Through an Example Subdataset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
Chapter 15 Crosstabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
15.1 Using the Crosstab Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
15.2 Working with Columns, Rows, and Measures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
15.2.1 Modifying Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
15.2.2 Understanding Measures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
15.3 Modifying Crosstab Element Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
15.4 Crosstab Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 299
15.5 Working with Crosstab Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
15.6 Using Crosstab Total Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
8
Jaspersoft Style Guide and FrameMaker Template
Chapter 16 Internationalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
16.1 Using a Resource Bundle Base Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
16.2 Retrieving Localized Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
16.3 Formatting Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
16.4 Deploying Localized Reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
16.5 Generating a Report Using a Specific Locale and Time Zone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
Chapter 17 Subreports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
17.1 Creating a Subreport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
17.1.1 Linking a Subreport to the Parent Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
17.1.2 Specifying the Subreport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
17.1.3 Specifying the Data Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
17.1.4 Passing Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
17.2 A Step-by-Step Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
17.3 Returning Values from a Subreport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
17.4 Using the Subreport Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
17.4.1 Create a New Report via the Subreport Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
17.4.2 Specifying an Existing Report in the Subreport Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
Chapter 18 Scriptlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
18.1 Understanding the JRAbstractScriptlet Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
18.2 Creating a Simple Scriptlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
18.3 Testing a Scriptlet in iReport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
18.4 Accessing iReport Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
18.5 Debugging a Scriptlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
18.6 Deploying Reports That Use Scriptlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
Chapter 19 Additional Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
19.1 Callout Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
19.1.1 Current Date Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
19.2 Page Number, Total Pages and Page X of Y Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
19.2.1 Page Number Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
19.2.2 Printing Page X of Y in a Single Textfield . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
19.3 Percentage Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
19.4 Using a Background Image as Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
19.5 How to Run the Samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
Appendix A Chart Theme Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
Introduction
9
CHAPTER 1INTRODUCTION
iReport Designer is an open source authoring tool that can create complex reports from any kind of Java application through
the JasperReports library. It is written in 100% pure Java and is distributed with source code according to the GNU General
Public License.
Through an intuitive and rich graphic interface, iReport lets you rapidly create any kind of report very easily. iReport enables
engineers who are just learning this technology to access all the functions of JasperReports, as well as helping skilled users to
save a lot of time during the development of very elaborate reports.
For Version 5.0, iReport was almost completely rewritten, with the new application based on the NetBeans rich client
platform. Even though the user interface appears pretty much the same, a complete new design of the iReport core and the use
of the NetBeans platform will allow us to quickly create new features, making iReport even easier to learn and use.
With this iReport Ultimate Guide you’ll learn how to add visual and analytic features to complex reports with charts, images,
and subreports. This informative guide has transformed many a newcomer into designers of pixel-perfect, complex, and highly
interactive reports. It is written and updated by Giulio Toffoli, iReport project founder and architect.
This chapter has the following sections:
Features of iReport
The iReport Community
JasperReports Commercial License
Code Used in This Book
1.1 Features of iReport
The following list describes some of the most important new features of iReport 5.0:
Support for relative dates.
HTML5 charts.
XML/A support of MSAS.
Nested tables.
Version 4.7 added the following features:
100% support of JasperReports XML tags.
WYSIWYG editor for the creation of reports. It has complete tools for drawing rectangles, lines, ellipses, textfields,
labels, charts, subreports and crosstabs.
Built-in editor with syntax highlighting for writing expressions.
Support for Unicode and non-Latin languages (Russian, Chinese, Japanese, Korean, etc.).
10
iReport Ultimate Guide
Browser for document structure.
Integrated report compiler, filler, and exporter.
Support for all databases accessible by JDBC.
Virtual support for all kinds of data sources.Wizard for creating reports and subreport automatically.
Support for document templates.
TrueType fonts support.
Support for localization.
Extensibility through plug-ins.
Support for charts.
Management of a library of standard objects (for example, numbers of pages).
Drag-and-drop functionality.
Unlimited undo/redo.
Wizard for creating crosstabs.
Styles library.
Integrated preview.
Error manager.
JasperServer repository explorer.
Integrated SQL and MDX query designer.
Additional features in Professional Edition.
Version 3.6 added support for visual components based on Adobe Flash.
Version 3.7 has these new features:
Instructions on installing iReport on Mac OSX.
Enhanced page formatting, including band features that enable multiple bands and subbands of the same type and a new
Page Format dialog.
Keep Together and Footer Position properties for groups.
Query executers and fields providers to enable you to use custom query languages.
1.2 The iReport Community
The iReport team comprises many skilled and experienced programmers who come from every part of the world. They work
daily to add new functionality and fix bugs. The iReport project site is at http://ireport.sourceforge.net. If you need help with
iReport, there is a discussion forum in English. This is the place where you can send requests for help and technical questions
about the use of the program, as well as post comments, discuss implementation choices, and propose new functionality. There
is no guarantee of a prompt reply, but requests are usually satisfied within a few days’ time. This service is free. If you need
information concerning commercial support, you can write to sales@jaspersoft.com.
Please report bugs at the following address: http://community.jaspersoft.com/bug-tracker
At the project site, there is a system to send requests for enhancement (RFE). There is also the ability to suggest patches and
integrative code. All members of the iReport team value feedback from the user community and seriously consider all
suggestions, criticism, and advice from iReport users.
1.3 JasperReports Commercial License
The Pro components of JasperReports Professional require a commercial license. iReport Professional includes a full-featured,
30-day evaluation license that must be replaced with the commercial license provided by Jaspersoft. The commercial license
can be installed using the License Manager.
Introduction
11
To open the License Manager select Help License Manager:
Click Install License and select the license file to use. iReport will copy the provided file in the user directory with the name
jasperreports.license. If the license is not valid, a message will explain the problem and what do to.
If you do not purchase the commercial license and the evaluation license expires, iReport shows the following message at
startup. You can still use iReport with the expired license, but you cannot run reports that use Pro components:
1.4 Code Used in This Book
JasperReports supports the following languages for expressions:
Java
JavaScript
Groovy
All the sample expressions used in this guide are written in JavaScript.
Figure 1-1 License Manager Dialog
Figure 1-2 License Manager Dialog When License Expires
12
iReport Ultimate Guide
Getting Started
13
CHAPTER 2GETTING STARTED
In this chapter you will learn the basic requirements for using iReport, where you can get it and how to install it.
This chapter has the following sections:
Platform Requirements
Downloads
Development Versions
Compiling iReport
Installing iReport
The Windows Installer
First iReport Execution
Creating a JDBC Connection
Creating Your First Report
2.1 Platform Requirements
iReport needs the Sun Java 2 SDK to run, Version 1.5 or newer. If you want to build the tool from the source code or write a
plug-in, you will also need NetBeans IDE and the NetBeans platform 6.5.1.
As for hardware, like all Java programs, iReport consumes a lot of RAM, so it is necessary to have at least 256 MB of memory
available as well as about 50 MB of free disk space.
Some features documented in this guide require Jaspersoft Professional software. The features are indicated with a special
note.
2.2 Downloads
You can download iReport from the dedicated project page on SourceForge.net, where you can always find the most recent
released iReport distributions (http://www.jaspersoft.com/jaspersoft-business-intelligence-software-trial). Four different
distributions are available:
iReport-x.x.x.zip. This is the official binary distribution in ZIP format.
In order to avoid problems with the file chooser in iReport, Windows Vista users should have Java 1.5.0_17-b04 or
newer installed. Windows 7 users should have Java 1.6.0_18-b03 or 1.7.0-b74.
14
iReport Ultimate Guide
iReport-x.x.x.tgz. This is the official binary distribution in TAR GZ format.
iReport-x-x-x-src.zip. This is the official distribution of source files in ZIP format.
iReport-x.x.x-windows-installer.exe. This is the official Win32 installer.
iReport-x.x.x.dmg. This is the official binary distribution for Mac OSX in Disk Image format.
x.x.x represents the version number of iReport*. Every distribution contains all needed libraries from third parties necessary to
use the program and additional files, such as templates and base documentation in HTML format.
iReport is also available as a native plug-in for NetBeans IDE 6.x. You can download the plug-in from SourceForge or
NetBeans.
At the time of writing we are planning an OS X distribution to support Macintosh systems; it may be available in the future.
2.3 Development Versions
If you want to test pre-release versions of iReport, you can directly access the developmental source repository with SVN. In
this case, you must have an SVN client (my favorite is Tortoise SVN). If you don’t have one, you will need to create an
account at http://community.jaspersoft.com/ in order to access the repository.
The URL of the SVN repository for iReport is:
http://anonsvn:anonsvn@community.jaspersoft.com/svn/repos/ireportfornetbeans
2.4 Compiling iReport
The distribution with sources contains a NetBeans project. In order to compile the project and run iReport, you need NetBeans
IDE and the platform 6.0.1 (or 6.5.1 starting from iReport 3.6.1). If you are using NetBeans 6.0, the platform is the same as the
IDE; otherwise you’ll need to download the platform separately at this URL:
http://download.netbeans.org/netbeans/6.0/final/zip/netbeans-6.0.1-200801291616-mml.zip
If you need to work with iReport 3.6.1 sources, you need NetBeans 6.5.1; otherwise, you can download the 6.5.1 platform
from the NetBeans site.
http://bits.netbeans.org/download/6.5.1/fcs/zip.html
The file to download is netbeans-6.5.1-200903060201-all-in-one.zip.
Download iReport-x.x.x-src.zip and unzip it in the directory of your choice, such as c:\devel (or /usr/devel on a UNIX system).
* Up to iReport 3.6.1, the version number contains the “nb” prefix (for “NetBeans”). This prefix was introduced when iReport was
rewritten on top of the NetBeans platform (version 3.1.0). The prefix has been removed starting with version 3.6.2.
Pre-release iReport source code is no longer available on SourceForge CVS Server.
Please note that NetBeans IDE is the development environment, while NetBeans 6.5.1 is the version of the platform
(which can be considered something like an external library or dependency; it has very little to do with the IDE).
iReport is built on NetBeans Rich Client Platform version 6.5.1. In order to build iReport you can use any version of
NetBeans IDE, but you need this specific NetBeans platform to successfully compile the source.
Getting Started
15
Run NetBeans IDE and open the iReport project (see Figure 2-1).
The project is actually a suite that contains several subprojects, or modules.
To run iReport, click the Run main project button on the tool bar.
Figure 2-1 NetBeans IDE project chooser
16
iReport Ultimate Guide
If you want to build all the distributions, run the create-ireport-distro target provided in the build script. To do it, select the
build.xml (Build Script) file located in the project folder Important Files. Right-click the file and select the appropriate target
to run (see Figure 2-2).
2.5 Installing iReport
If you download the binary version of iReport, do the following:
1. Unpack the distribution archive into the directory of your choice; for example, to c:\devel (or /usr/devel on a UNIX
system).
2. Open a command prompt or a shell, go to the directory where the archive was unpacked, change to the iReport directory,
then to the \bin subdirectory, and enter:
ireport.exe
In Unix, use the chmod +x command to make the installation script executable, then, in the root directory, enter:
./ireport
Figure 2-2 Build script containing a set of targets to create several iReport distributions
Getting Started
17
2.6 The Windows Installer
iReport provides a convenient Windows installer created using NSIS, the popular installer from Nullsoft. To install iReport,
double-click iReport-nb-x.x.x-windows-installer.exe to bring up the screen shown in Figure 2-4.
Click Next and follow the instructions in the Install wizard until the installation is complete (Figure 2-5).
Figure 2-3 Windows Installer – Step 1
Figure 2-4 Windows Installer — Step 2
18
iReport Ultimate Guide
After the installation, there will be a new menu item in the Programs menu (Start Programs Jaspersoft iReport-nb-
x.x.x).
The installer creates a shortcut to launch iReport, linking the shortcut to iReport.exe (present in the /bin directory under the
Jaspersoft home directory).
Figure 2-5 Windows Installer - Last Step
You can install more than one version of iReport on your machine at the same time, but all the versions will share the
same configuration files.
Getting Started
19
2.7 Installing iReport on Mac OSX
Mac OSX does not require any special installation procedure, just double-click the DMG (Disk Image) archive and drag
iReport into the Applications folder.
To run iReport, double-click the iReport icon.
2.8 First iReport Execution
When you run iReport for the first time, you will need to configure a couple of options in order to start designing reports,
including a data source to be used with the reports and, optionally, the location of the external programs to preview the reports
(only if you don’t want to use the internal preview).
Figure 2-6 The Disk Image mounted on Mac OSX
20
iReport Ultimate Guide
To display the window shown here in Figure 2-7, run iReport and select Tools Options. I will discuss all the options
shown in this panel in later chapters. For now, click the Viewers tab (see Figure 2-8) and configure the applications that you
will use to view your output reports.
Figure 2-7 Options Window – General Options
Getting Started
21
Test the configuration by creating a new blank report:
1. Select File New empty report.
2. Select where to save it and confirm.
3. Click the Preview button on the tool bar.
If everything is okay, iReport generates a Jasper file and displays a preview of a blank page. This means you have installed and
configured iReport correctly.
On Windows and Mac OSX it is not necessary to configure the viewers. If they are not configured, the system default is used
to open the generated files.
2.9 Creating a JDBC Connection
The most common data source for filling a report is a relational database, so, next, you will see how to set up a JDBC
connection in iReport:
1. Click Select Tools Reports and click the New button in the window with the connections list. A new window will
appear for configuration of the new connection (see Figure 2-9).
Figure 2-8 Options Window – Viewers
iReport stores report templates as XML files, with extension of .jrxml (JRXML files). Compiled versions of the
templates are stored as binary files, with the extension .jasper (Jasper files). The latter are used to actually generate
the reports.
22
iReport Ultimate Guide
2. Select Database JDBC connection and click Next.
3. In the Database JDBC Connection window, enter the connection name (for example, “My new connection”) and select the
right JDBC driver.
iReport recognizes the URL syntax of many JDBC drivers. You can automatically create the URL by entering the server
address and database name in the corresponding boxes and clicking the Wizard button.
Figure 2-9 Data Source Type Selection
Getting Started
23
4. To complete the connection configuration, enter the username and password for access to the database.
If you want to save the password, select the Save password check box.
I suggest that you test the connection configuration before moving on, which you can do by clicking the Test button.
iReport provides the JDBC driver for the following SQL-compliant database systems:
HSQL
MySQL
PostgreSQL
If iReport returns a ClassNotFound error, it is possible that there is no JAR archive (or ZIP) in the classpath that contains the
selected database driver. In this case, there are two options:
Adding the required JAR to the iReport classpath.
To extend the iReport classpath, select the menu item Tools Options, go to the classpath tab under the iReport
category, and add the JAR to the list of paths.
Registering the new driver through the service window.
If you prefer this second way, open the services window (Window Services or CTRL+5), select the Databases node,
then the Drivers node.
Right-click the Drivers node and select New Driver. The dialog shown in Figure 2-11 will pop up.
Figure 2-10 JDBC Connection Using a Built-in JDBC Driver
24
iReport Ultimate Guide
Resume the testing without closing iReport by copying the JDBC driver into the /lib directory and clicking Test again. iReport
automatically locates the required JAR file and loads the driver from it. In Chapter 10, I will explain the configuration
methods for various data sources in greater detail.
If the test is successful, click the Save button to store the new connection.
The connection will appear in the data source drop-down list in the main tool bar (Figure 2-12). Select it to make it the active
connection.
Another way to set the active connection is by opening the data source window (Figure 2-12):
1. Select the Tools Report data sources menu item (or by clicking the button on the tool bar next to the data sources drop-
down list).
2. Select the data source that you want to make active:
3. Click Set as default.
The selected data source is the one used to fill the report and perform other operations, such as the acquisition of the fields
selected through SQL queries. There is no strict binding between a report and a data source, so you can run a report with
different data sources, but only one at time. Later, we will see how subreports can be used to create a report that uses multiple
data sources.
Figure 2-11 Oracle Driver Loaded from an External JAR
Figure 2-12 Data Sources Window
Getting Started
25
The Data Sources drop-down menu allows you to select the active data source; the button on the left opens the Data Sources
window:
2.10 Creating Your First Report
Now that you have installed and configured iReport and prepared a JDBC connection to the database, you will proceed to
create a simple report using the Wizard.
For this example and many of those following, you will use HSQLDB, a small relational database written in Java and supplied
with a JDBC driver. You can learn more about this small jewel by visiting the HSQLDB web site.
2.10.1 Using the Sample Database
For sample reports, we will use the sample database that comes with JasperReports.
Download JasperReports (the biggest distribution) and unpack it. Open a command prompt (or a shell) and change to the
<JasperReports installation folder>/demo/hsqldb. I
If you have Ant (and you know what it is), just run:
ant runServer
Otherwise, run this command (all in a single line):
java -cp ..\..\lib\hsqldb-1.7.1.jar org.hsqldb.Server
The database server will start and we will be ready to use it with iReport.
2.10.2 Using the Report Wizard
The table below lists the parameters you should use to connect to the sample database:
When the password is blank, as in this case, remember to set the Save password check box when configuring the connection.
1. Click File Report Wizard. This loads a wizard (Figure 2-14) for the step-by-step creation of a report, starting with the
selection of the template followed by the selection of the name and the location of the new report.
Figure 2-13 Data Sources Drop-Down Menu
Parameter Value
Name JasperReports Sample
JDBC Driver org.hsqldb.jdbcDriver
JDBC URL jdbc:hsqldb:hsql://localhost
Username sa
Password
26
iReport Ultimate Guide
2. Select the template and click Launch Report Wizard to proceed with the report creation. (You can create a simple report
that duplicates the selected template just by clicking Open this Template. However, we’ll use the wizard for this
example.)
Figure 2-14 Report Wizard – Template Selection
Figure 2-15 Report Wizard – New Report Name and Location
Getting Started
27
3. In the third step, select the JDBC connection we configured in the previous step. The wizard will detect that we are
working with a connection that allows the use of SQL queries and will prompt a text area to specify an SQL query
(Figure 2-16). Optionally, we can design the query visually by clicking Design query.
We assume that you know at least a bit of SQL, so we will directly enter a simple query, as follows:
select * from address order by city
4. Click Next. The clause “order by” is important to the following choice of sort order (I will discuss the details a little later).
iReport reads the fields of the addresses table and presents them in the next screen of the Wizard, as shown in
Figure 2-17.
Figure 2-16 Report Wizard – SQL Query
28
iReport Ultimate Guide
5. Select the fields you wish to include and click Next.
6. Now that you have selected the fields to put in the report, you are prompted to choose which fields to use for sorting, if
any (see Figure 2-17).
Using the wizard, you can create up to four groups. You can define more fields later. (In fact, it is possible to set up an
arbitrary number of groupings.)
Figure 2-17 Report Wizard – Fields Selection
Getting Started
29
7. For this first report, define a simple grouping on the CITY field, as shown in Figure 2-18.
8. When done, click Next.
Figure 2-18 Report Wizard – Grouping
Figure 2-19 Main Preview and Design Window
30
iReport Ultimate Guide
9. The last screen of the wizard will appear, and it will tell you the outcome of the operation. Click Finish to create the
report, which will appear in the iReport central area, ready to be generated, as shown below.
10. Click the Preview button to see the final result.
When you click Preview, iReport compiles the report, generating the JASPER file and executing the report against the
specified data source. You can track the progress in the output window, which is below the main window.
If, for some reason, the execution fails, you can see a set of problems in the Report Problems window, and other error tracking
information (for example, a full stack trace) in the iReport output window.
In this example, everything should work just fine, and you should see the report in the preview as shown above (Figure 2-19).
Also note:
You can save the report by clicking on the disk icon in the window tool bar. iReport can save reports in several formats,
including PDF and HTML.
To automatically export the report in a particular format and run the appropriate viewer application, select a format from
the Preview menu.
To run the report again from the preview window, click the Reload button in the preview tool bar, or, if you change the
report design, save the design and click Preview.
Basic Notions of JasperReports
31
CHAPTER 3BASIC NOTIONS OF JASPERREPORTS
The heart of iReport is JasperReports, an open source library developed and maintained by Jaspersoft Corporation under the
direction of Teodor Danciu and Lucian Chirita. It is the most widely distributed and powerful free software library for report
creation available today.
In this chapter, I will illustrate JasperReports’s base concepts for a better understanding of how iReport works.
The JasperReports API, the XML syntax for report definition, and all the details for using the library in your own programs are
documented very well in The JasperReports Ultimate Guide. This guide is available from Jaspersoft. Other information and
examples are directly available on the official JasperReports site at http //jasperreports.sourceforge.net.
JasperReports is published under the LGPL license, which is less restrictive a GPL license. JasperReports can be freely used
on commercial programs without buying very expensive software licenses and without remaining trapped in the complicated
net of open source licenses. This is fundamental when reports created with iReport have to be used in a commercial product; in
fact, programs only need the JasperReports library to produce prints, which work something like a run time executable.
On the other hand, iReport is distributed with a GPL license. Without the appropriate commercial license (available upon
request), you can only use iReport as a development tool, and only programs published under the terms of the GPL license
may include iReport as a component.
This chapter has the following sections:
The Report Life Cycle
JRXML Sources and Jasper Files
Data Sources and Print Formats
Compatibility Between Versions
Expressions
Using Java as a Language for Expressions
Using Groovy as a Language for Expressions
Using JavaScript as a Language for Expressions
A Simple Program
3.1 The Report Life Cycle
When we think about a report, only the final document comes to mind, such as a PDF or Excel file. But this is only the final
stage of a report lifecycle, which starts with the report design. Designing a report means creating some sort of template, such
as a form where we leave blank space that can be filled with data. Some portions of a page defined in this way are reused,
others stretch to fit the content, and so on.
32
iReport Ultimate Guide
When we are finished, we save this template as an XML file sub-type that we call JRXML (“JR” for JasperReports). It
contains all the basic information about the report layout, including complex formulas to perform calculations, an optional
query to retrieve data out of a data source, and other functionality we will discuss in detail in later chapters.
A JRXML cannot be used as-is. For performance reasons, and for the benefit of the program that will run the report, iReport
compiles the JRXML and saves it as an executable binary, a JASPER file. A JASPER file is the template that JasperReports
uses to generate a report melding the template and the data retrieved from the data source. The result is a “meta print”—an
interim output report—that can then be exported in one or more formats, giving life to the final document.
The life cycle can be divided into two distinct action sets:
Tasks executed during the development phase (design and planning of the report, and compilation of a Jasper file source,
the JRXML).
Tasks that must be executed in run time (loading of the Jasper file, filling of the report, and export of the print in a final
format).
The main role of iReport in the cycle is to design a report and create an associated JASPER file, though it is able to preview
the result and export it in all the supported formats. iReport also provides support for a wide range of data sources and allows
the user to test their own data sources, thereby becoming a complete environment for report development and testing.
3.2 JRXML Sources and Jasper Files
As already explained, JasperReports defines a report with an XML file. In previous versions, JasperReports defined the XML
syntax with a DTD file (jasperreport.dtd). Starting with Version 3.0.1, JasperReports changed the definition method to allow
for support of user defined report elements. The set of tags was extended and the new XML documents must be validated
using an XML-Schema document (jasperreport.xsd).
Table 3-1
A JRXML file is composed of a set of sections, some of them concerning the report’s physical characteristics, such as the
dimension of the page, the positioning of the fields, and the height of the bands; and some of them concerning the logical
characteristics, such as the declaration of the parameters and variables, and the definition of a query for data selection.
The syntax has grown more and more complicated with the maturity of JasperReports. This is why many times a tool like
iReport is indispensable.
The following figure shows the source code of the report described in the previous chapter (Figure 2-19):
.Code Example 3-1 A simple JRMXL file example
<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://
jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/
xsd/jasperreport.xsd" name="My first report" pageWidth="595" pageHeight="842"
columnWidth="535" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<queryString language="SQL">
<![CDATA[select * from address order by city]]>
</queryString>
<field name="ID" class="java.lang.Integer">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="FIRSTNAME" class="java.lang.String">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="LASTNAME" class="java.lang.String">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
Basic Notions of JasperReports
33
<field name="STREET" class="java.lang.String">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<field name="CITY" class="java.lang.String">
<fieldDescription><![CDATA[]]></fieldDescription>
</field>
<group name="CITY">
<groupExpression><![CDATA[$F{CITY}]]></groupExpression>
<groupHeader>
<band height="27">
<staticText>
<reportElement mode="Opaque" x="0" y="0" width="139" height="27"
forecolor="#FFFFFF" backcolor="#000000"/>
<textElement>
<font size="18"/>
</textElement>
<text><![CDATA[CITY]]></text>
</staticText>
<textField hyperlinkType="None">
<reportElement mode="Opaque" x="139" y="0" width="416" height="27"
forecolor="#FFFFFF" backcolor="#000000"/>
<textElement>
<font size="18" isBold="true"/>
</textElement>
<textFieldExpression class="java.lang.String"><![CDATA[$F{CITY}]]>
</textFieldExpression>
</textField>
</band>
</groupHeader>
<groupFooter>
<band height="8">
<line direction="BottomUp">
<reportElement key="line" x="1" y="4" width="554" height="1"/>
</line>
</band>
</groupFooter>
</group>
<background>
<band/>
</background>
<title>
<band height="58">
<line>
<reportElement x="0" y="8" width="555" height="1"/>
</line>
<line>
<reportElement positionType="FixRelativeToBottom" x="0" y="51" width="555"
height="1"/>
</line>
Code Example 3-1 A simple JRMXL file example, continued
34
iReport Ultimate Guide
<staticText>
<reportElement x=”65” y=”13” width ”424” height=”35”/>
<textElement textAlignment=”Center”>
<font size=”26” isBold=”true”/>
</textElement>
<text><![CDATE[Classic template]]> </text>
</staticText>
</band>
</title>
<pageHeader>
<band/>
</pageHeader>
<columnHeader>
<band height="18">
<staticText>
<reportElement mode="Opaque" x="0" y="0" width="138" height="18"
forecolor="#FFFFFF" backcolor="#999999"/>
<textElement>
<font size="12"/>
</textElement>
<text><![CDATA[ID]]></text>
</staticText>
<staticText>
<reportElement mode="Opaque" x="138" y="0" width="138" height="18"
forecolor="#FFFFFF" backcolor="#999999"/>
<textElement>
<font size="12"/>
</textElement>
<text><![CDATA[FIRSTNAME]]></text>
</staticText>
<staticText>
<reportElement mode="Opaque" x="276" y="0" width="138" height="18"
forecolor="#FFFFFF" backcolor="#999999"/>
<textElement>
<font size="12"/>
</textElement>
<text><![CDATA[LASTNAME]]></text>
</staticText>
<staticText>
<reportElement mode="Opaque" x="414" y="0" width="138" height="18"
forecolor="#FFFFFF" backcolor="#999999"/>
<textElement>
<font size="12"/>
</textElement>
<text><![CDATA[STREET]]></text>
</staticText>
</band>
</columnHeader>
Code Example 3-1 A simple JRMXL file example, continued
Basic Notions of JasperReports
35
<detail>
<band height="20">
<textField hyperlinkType="None">
<reportElement x="0" y="0" width="138" height="20"/>
<textElement>
<font size="12"/>
</textElement>
<textFieldExpression class="java.lang.Integer"><![CDATA[$F{ID}]]>
</textFieldExpression>
</textField>
<textField hyperlinkType="None">
<reportElement x="138" y="0" width="138" height="20"/>
</textField>
<textElement>
<font size="12"/>
</textElement>
<textFieldExpression class="java.lang.String"><![CDATA[$F{FIRSTNAME}]]>
</textFieldExpression>
<textField hyperlinkType="None">
<reportElement x="276" y="0" width="138" height="20"/>
<textElement>
<font size="12"/>
</textElement>
<textFieldExpression class="java.lang.String"><![CDATA[$F{LASTNAME}]]>
</textFieldExpression>
</textField>
<textField hyperlinkType="None">
<reportElement x="414" y="0" width="138" height="20"/>
<textElement>
<font size="12"/>
</textElement>
<textFieldExpression class="java.lang.String"><![CDATA[$F{STREET}]]>
</textFieldExpression>
</textField>
</band>
</detail>
<columnFooter>
<band/>
</columnFooter>
<pageFooter>
<band height="26">
<textField evaluationTime="Report" pattern="" isBlankWhenNull="false"
hyperlinkType="None">
<reportElement key="textField" x="516" y="6" width="36" height="19"
forecolor="#000000" backcolor="#FFFFFF"/>
<textElement>
<font size="10"/>
</textElement>
Code Example 3-1 A simple JRMXL file example, continued
36
iReport Ultimate Guide
During compilation of the JRXML file (using some JasperReports classes), the XML is parsed and loaded in a JasperDesign
object, which is a rich data structure that allows you to represent the exact XML contents in memory. Without going into
details, regardless of which language is used for expressions inside the JRXML, JasperReports creates a special Java class that
represents the whole report. The report is then compiled, instanced and serialized in a JASPER file, ready for loading at any
time.
JasperReports’s speedy operation is due to all of a report’s formulas being compiled into Java-native bytecode and the report
structure being verified during compilation instead of run time. The JASPER file does not contain extraneous resources, such
as images used in the report, resource bundles to run the report in different languages, or extra scriptlets and external style
definitions. All these resources must be provided by the host application and located at run time.
<textFieldExpression class="java.lang.String"><![CDATA["" +
$V{PAGE_NUMBER}]]></textFieldExpression>
</textField>
<textField pattern="" isBlankWhenNull="false" hyperlinkType="None">
<reportElement key="textField" x="342" y="6" width="170" height="19"
forecolor="#000000" backcolor="#FFFFFF"/>
<box>
<topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
</box>
<textElement textAlignment="Right">
<font size="10"/>
</textElement>
<textFieldExpression class="java.lang.String"><![CDATA["Page " +
$V{PAGE_NUMBER} + " of "]]></textFieldExpression>
</textField>
<textField pattern="" isBlankWhenNull="false" hyperlinkType="None">
<reportElement key="textField" x="1" y="6" width="209" height="19"
forecolor="#000000" backcolor="#FFFFFF"/>
<box>
<topPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<leftPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<bottomPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
<rightPen lineWidth="0.0" lineStyle="Solid" lineColor="#000000"/>
</box>
<textElement>
<font size="10"/>
</textElement>
<textFieldExpression class="java.util.Date"><![CDATA[new Date()]]>
</textFieldExpression>
</textField>
</band>
</pageFooter>
<summary>
<band/>
</summary>
</jasperReport>
Code Example 3-1 A simple JRMXL file example, continued
Basic Notions of JasperReports
37
3.3 Data Sources and Print Formats
Without a means of supplying content from a dynamic data source, even the most sophisticated and appealing report would be
useless. JasperReports allows you to specify fill data for the output report in two ways: parameters and data sources. Either
kinds of data are presented by means of a generic interface named JRDataSource, as shown in Figure 3-1.
Chapter Chapter 10, “Data Sources and Query Executers,” on page 153 is dedicated to data sources; it explains how they
can be used in iReport and how it is possible to define custom data sources (in case those supplied with JasperReports are not
right for your requirements).
JRDataSource allows a set of records that are organized in tables (rows and columns) to be read. It enables JasperReports to
fill a report with data from an explicit data source, using a JDBC connection (already instanced and opened) to whichever
relational database you want to run a SQL query on (which is specified in the report).
If the data (passed through a data source) don't meet the requirements of the user, that is, when it is necessary to specify
particular values to condition the report’s execution, it is possible to produce name/value pairs to “transmit” to the print
engine. These pairs are named parameters, and they have to be “preventively declared” in the report. Through fillManager,
it is possible to join a JASPER file and a data source in a JasperPrint object. This object is a meta-print that can create a real
print after you have exported it in the desired format through appropriate classes that implement the JRExporter interface.
JasperReports puts at your disposal different pre-defined exporters, such as those for creating files in such formats as PDF,
XLS, CVS, XML, RTF, ODF, text, HTML and SWF. Through the JRViewer class, you can view the print directly on the
screen and print a hardcopy.
3.4 Compatibility Between Versions
When a new version of JasperReports is distributed, some classes usually change. These modified classes typically impact the
XML syntax and the JASPER file structure.
Before JasperReports 1.1.0, this was a serious problem and a major upgrade deterrent, since it required recompiling all the
JRXML files in order to be used with the new library version. Things changed after the release of Version 1.1.0, after which
JasperReports assured backwards compatibility, that is, the library is able to understand and execute any JASPER file
generated with a previous version of JasperReports.
Figure 3-1 Data source and parameter Flows for Report Creation
38
iReport Ultimate Guide
With JasperReports 3.1, the JRXML syntax moved from a DTD-based definition to XML-based schema. The XML source
declaration syntax now references a schema file, rather than a DTD. Based on what we said previously, this is not a problem
since JasperReports assures backwards compatibility. However, many people have been used to designing reports with early
versions of iReport then generating the reports by compiling JRXML in JasperReports. This was always a risky operation, but
it was still valid because the user was not using a new tag in the XML. With the move to an XML schema, the JRXML output
of iReport 3.1.1 and newer can only be compiled with a JasperReports 3.1.0 or later.
3.5 Expressions
Though I designed iReport to be useful for non-technical report designers, many settings in a report are defined using formulas
(such as conditions to hide an element, special calculations, text processing, and so on) that require a minimum knowledge of
a scripting language.
Fortunately, formulas can be written in at least three languages, two of which (JavaScript and Groovy) are pretty simple and
can be used without knowledge of programming methods.
All of the formulas in JasperReports are defined through expressions. The default expression language is Java, but I suggest
that you design your projects with JavaScript or Groovy. Both hide a lot of the Java complexity and are definitively the
languages to use if you don’t know Java. The language is a property of the document, so, to set it, select the document root
node in the Outline view and choose your language in the Language property in the Properties view. We will go through all
the languages in the following sections, but let’s concentrate for a moment on our definition of an “expression,” in particular
the type you will declare for it and why that is important in JasperReports.
An expression is just a formula that operates on some values and returns a result. Think of an expression as the formula you
might define for a spreadsheet cell. A cell can have a simple value or you can use a complex formula that refers to other
values; in a spreadsheet you would refer to values contained in other cells, whereas in JasperReports you will use the report
fields, parameters, and variables. The main point is that whatever you have in your expression, when it is computed it gives a
value as result (which can be null; that’s still a value).
3.5.1 The Type of an Expression
The type of an expression is the nature of the value resulting from it; the type is determined by the context in which the
expression is used. For example, if your expression is used to evaluate a condition, the type of the expression should be
Boolean (true or false); if you are creating an expression that should be displayed in a textfield, it will probably be a String or
a number (Integer or Double). We could simplify the declaration of types by limiting them to text, numbers, Booleans, and
generic object values. Unfortunately, JasperReports is a bit more formal and in many cases you have to be very precise when
setting the type of your expression.
So far, we are discussing only Java types (regardless of the language used). Some of the most important types are:
java.lang.Boolean Defines an Object that represents a boolean value such as true and
false
java.lang.Byte Defines an Object that represents a byte
java.lang.Short Defines an Object that represents an short integer
java.lang.Integer Defines an Object that represents integer numbers
java.lang.Long Defines an Object that represents long integer numbers
java.lang.Float Defines an Object that represents floating point numbers
java.lang.Double Defines an Object that represents real numbers
java.lang.String Defines an Object that represents a text
Basic Notions of JasperReports
39
As noted, if the expression is used to determine the value of a condition that determines, for instance, whether an element
should be printed, the return type will be java.lang.Boolean; to create it, you need an expression that returns an instance of
a Boolean object. Similarly, if I’m writing the expression to show a number in a textfield, the return type will be
java.lang.Integer or java.lang.Double.
Fortunately, JavaScript and Groovy are not particularly formal about types, since they are not typed languages; the language
itself treats a value in the best way by trying to guess the value type or by performing implicit casts (conversion of the type).
3.5.2 Expression Operators and Object Methods
Operators in Java, Groovy and JavaScript are similar because these languages share the same basic syntax. Operators can be
applied to a single operand (unary operators) or on two operands (binary operators).
The table shows a number of operators. This is not a complete list; they are the ones I suggest. For instance, there is a unary
operator to add 1 to a variable (++), but in my opinion it is not easy to read and can be replaced easily with x + 1. Better, no?
Within the expression, you can the syntax that’s summarized in Table 3-3 to refer to the parameters, variables, and fields
which are defined in the report.
java.util.Date Defines an Object that represents a date or a timestamp
java.lang.Object A generic java Object
Table 3-2 Expression operators
Operator Description Example
+Sum (it can be used to sum two numbers or to concatenate two strings) A + B
-Subtraction A - B
/Division A / B
%Rest, it returns the rest of an integer division A % B
|| Boolean operator OR A || B
&& Boolean operator AND A && B
== Equals*
* In Java the == operator can only be used to compare two primitive values. With objects, you need to use the special
method “equals”; for example, you cannot write an expression like “test” == “test”, you need to write “test”.equals(“test”).
!= can only be used to compare two primitive values, as well.
A == B
!= Not equals*A != B
!Boolean operator NOT !A
Table 3-3 Syntax for referring to report objects
Syntax Description
$F{name_field} Specifies the name_field field ("F" means field).
$V{name_variable} Specifies the name_ variable variable.
$P{name_parameter} Specifies the name_parameter parameter.
$P!{name_parameter} Special syntax used in the report SQL query to indicate that the parameter does not
have to be dealt as a value to transfer to a prepared statement, but that it represents a
little piece of the query.
$R{resource_key} Special syntax for localization of strings.
40
iReport Ultimate Guide
We will describe the nature of fields, variables, and parameters in the next chapter. For now we just have to keep in mind that
they always represent objects (that is, they can have a null value) and that you specify their type when you declare them within
a report. Version 0.6.2 of JasperReports introduced a new syntax: $R{resource_key}. This is used to localize strings. I will
discuss this at greater lengths in Chapter Chapter 16, “Internationalization,” on page 305.
In spite of the possible complexity of an expression, usually it is a simple operation that returns a value. It is not a snippet of
code, or a set of many instructions, and you cannot use complex constructs or flow control keywords, such as switches, loops,
for and while cycles, if and else.
Be that as it may, there is a simple if-else expression construct that is very useful in many situations. An expression is just an
arbitrary operation (however complicated) that returns a value. You can use all the mathematical operators or call object
methods, but at any stage the expression must represent a value. In Java, all these operators can be applied only to primitive
values, except for the sum operator (+). The sum operator can be applied to a String expression with the special meaning of
“concatenate”. So, for example:
$F{city} + “, ” + $F{state}
will result in a string like this:
San Francisco, California
All the objects in an expression may include methods. A method can accept zero or more arguments, and it can return or not a
value; in an expression you can use only methods that return a value (otherwise you would have nothing to return from your
expression). The syntax of a method call is:
Object.method(argument1, argument2, and so on.)
Some examples:
All the methods of each object are usually explained in a set of documents called “Javadocs;” they are freely available on the
Internet.
You can use parentheses to isolate expressions and make the overall expression more readable.
3.5.3 Using an If-Else Construct in an Expression
A way to create an if-else-like expression is by using the special question mark operator. Here is a sample:
(($F{name}.length() > 50) ? $F{name}.substring(0,50) : $F{name})
The syntax is (<condition>) ? <value on true> : <value on false>. It is extremely useful, and the good news is
that it can be recursive, meaning that the value on true and false can be represented by another expression which can be a
new condition:
(($F{name}.length() > 50) ?
(($F{name}.startsWidth(“A”)) ? “AAAA” : “BBB”)
:
$F{name})
This expression returns the String “AAAA” when the value of the field name is longer than 50 characters and starts with A,
returns BBB if it is longer than 50 characters but does not start with A, and, finally, returns the original field value if neither of
these conditions is true.
Despite the possible complexity of an expression (having multiple if-else instructions and so on), it can be insufficient to
define a needed value. For example, if you want to print a number in Roman numerals or give back the name of the weekday
Expression Result
“test”.length() 4
“test”.substring(0, 3) “tes”
“test”.startsWith(“A”) false
“test”.substring(1, 2).startsWith(“e”) true
Basic Notions of JasperReports
41
of a date, it is possible to transfer the elaborations to an external Java class method, which must be declared as static, as shown
in the following:
MyFormatter.toRomanNumber( $F{MyInteger}.intValue() )
The function operand toRomanNumber is a static method of the MyFormatter class, which takes an int as argument (the
conversion from Integer to int is done by means of the intValue() method; it is required only when using Java as language)
and gives back the Roman version of a number in a lace.
This technique can be used for many purposes; for example, to read the text from a CLOB field or to add a value into a
HashMap (a convenient Java object that represents a set of key/value pairs).
3.6 Using Java as a Language for Expressions
First of all, there is no reason to prefer Java over other languages when working with iReport. It is the first language supported
by JasperReports and this is the only reason for which it is still the commonly-used language (and the default one).
Following are some examples of Java expressions:
“This is an expression”
new Boolean(true)
new Integer(3)
(($P{MyParam}.equals("S")) ? "Yes" : "No")
The first thing to note is that each of these expressions represents a Java Object, meaning that the result of each expression is a
non-primitive value. The difference between an object and a primitive value makes sense only in Java, but it is very important:
a primitive value is a pure value like the number 5 or the Boolean value true. Operations between primitive values have as a
result a new primitive value, so the expression:
5+5
results in the primitive value 10. Objects are complex types that can have methods, can be null, and must be “instanced” with
the keyword “new” most of the time. In the second example above, for instance (new Boolean(true)), we must wrap the
primitive value true in an object that represents it.
By contrast, in a scripting language such as Groovy and JavaScript, primitive values are automatically wrapped into objects, so
the distinction between primitive values and objects wanes. When using Java, the result of our expression must be an object,
which is why the expression 5+5 is not legal as-is but must be fixed with something like this:
new Integer( 5 + 5 )
The fix creates a new object of type Integer representing the primitive value 10.
So, if you use Java as the default language for your expressions, remember that expressions like the following are not valid:
3 + 2 * 5
true
(($P{MyParam} == 1) ? "Yes" : "No")
These expressions don’t make the correct use of objects. In particular, the first and the second expressions are not valid
because they are of primitive types (integer in the first case and boolean in the second case) which do not produce an
object as a result. The third expression is not valid because it assumes that the MyParam parameter is a primitive type and that
it can be compared through the == operator with an int, but it cannot. In fact, we said that parameters, variables, and fields are
always objects and primitive values cannot be compared or used directly in a mathematical expression with an object.
Since JasperReports is compiled to work with Java 1.4, the auto-boxing functionality of Java 1.5, that would in some cases
solve the use of objects as primitive values and vice versa, is not leveraged.
3.7 Using Groovy as a Language for Expressions
The modular architecture of JasperReports provides a way to plug in support for languages other than Java. By default, the
library supports two additional languages: Groovy and JavaScript (the latter starting with version 3.1.3).
42
iReport Ultimate Guide
Groovy is a full language for the Java 2 Platform. Inside the Groovy language you can use all classes and JARs that are
available for Java. Table 3-4 compares some typical JasperReports expressions written in Java and Groovy.
The following is a correct Groovy expression:
new JREmptyDataSource($F{num_of_void_records})
JREmptyDataSource is a class of JasperReports that creates an empty record set (meaning with the all fields set to null). You
can see how you can instance this class (a pure Java class) in Groovy without any problem. At the same time, Groovy allows
you to use a simple expression like this one:
5+5
The language automatically encapsulates the primitive value 10 (the result of that expression) in a proper object. Actually, you
can do more: you can treat this value as an object of type String and create an expression such as:
5 + 5+ ”my value”
Whether or not such an expression resolves to a rational value, it is still a legal expression and the result will be an object of
type String with the value:
10 my value
Hiding the difference between objects and primitive values, Groovy allows the comparison of different types of objects and
primitive values, such as the legal expression:
$F{Name} == “John”
This expression returns true or false, or, again:
Groovy provides a way to greatly simplify expressions and never complains about null objects that can crash a Java expression
throwing a NullPointerException. It really does open the doors of JasperReports to people who don’t know Java.
3.8 Using JavaScript as a Language for Expressions
JavaScript is a popular scripting language with a syntax very similar to Java and Groovy. The support for JavaScript has been
requested for a long time from the community and was finally introduced in JasperReports 3.1.2, using the open source Rhino
JavaScript implementation.
JavaScript has a set of functions and object methods that in some cases differ from Java and Groovy. For example, the method
String.startsWith(...) does not exist in JavaScript. The good news is that you can still use Java objects in JavaScript. A
simple example is:
Table 3-4 Groovy and Java code samples
Expression Java Groovy
Field $F{field_name} $F{field_name}
Sum of two
double fields
new Double($F{f1}.doubleValue() + $F{f2}.doubleValue()) $F{f1} + $F{f2}
Comparison of
numbers
new Boolean($F{f}.intValue() == 1) $F{f} == 1
Comparison of
strings
new Boolean($F{f} != null && $F{f}.equals("test")) $F{f} == "test"
$F{Age} > 18 Returns true if the Age object interpreted as a number is greater than
18.
“340” < 100 Always returns false.
“340”.substring(0,2) < 100 Always returns true (since the substring method call will produce the
string “34”, which is less than 100).
Basic Notions of JasperReports
43
(new java.lang.String("test")).startsWith("t")
This is a valid JavaScript expression. As you can see, we are able to create a Java object (in this case a java.lang.String)
and use its methods.
JavaScript is the best choice for people who have absolutely no knowledge of other languages, since it is easy to learn and
there are plenty of JavaScript manuals and references on the web. The other significant advantage is that it is not interpreted at
run time, but generates pure Java byte-code, instead. As a result, it produces almost the same performance as Java itself.
3.9 Using JasperReports Extensions in iReport
JasperReports provides several ways to extend its functionality. In general, extensions (like components, fonts, query
executors, chart themes, and so on) are packaged in JARs. To use these extensions in iReport, just add the required JARs to the
iReport classpath. The iReport classpath is composed of static and reloadable paths. Extensions must be set as static paths,
while other objects which don’t require a proper descriptor or special loading mechanism (such as scriptlets and custom data
sources) can be reloadable.
3.10 A Simple Program
I finish this introduction to JasperReports by presenting an example of a simple program that shows how to produce a PDF file
from a Jasper file using a data source named JREmptyDataSource, which is a utility data source that provides zero or more
records without fields. The file test.jasper, referenced in the example, is the compiled version of the code in Code
Example 3-1.
Code Example 3-2 JasperTest.java
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.export.*;
import java.util.*;
public class JasperTest
{
public static void main(String[] args)
{
String fileName = "/devel/examples/test.jasper";
String outFileName = "/devel/examples/test.pdf";
HashMap hm = new HashMap();
try
{
JasperPrint print = JasperFillManager.fillReport(
fileName,
hm,
new JREmptyDataSource());
JRExporter exporter =
new net.sf.jasperreports.engine.export.JRPdfExporter();
44
iReport Ultimate Guide
exporter.setParameter(
JRExporterParameter.OUTPUT_FILE_NAME,
outFileName);
exporter.setParameter(
JRExporterParameter.JASPER_PRINT,print);
exporter.exportReport();
System.out.println("Created file: " + outFileName);
}
catch (JRException e)
{
e.printStackTrace();
System.exit(1);
}
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
}
Code Example 3-2 JasperTest.java, continued
Report Structure
45
CHAPTER 4REPORT STRUCTURE
In this chapter we will analyze the report structure, the underlying template that determines the style and organization of a
report. We will see the parts that compose it and how they behave in relation to input data as iReport creates an output report.
This chapter has the following sections:
Bands
Working with Bands
Summary
4.1 Bands
A report is defined by means of a type page. This page is divided into different horizontal portions named “bands.” When the
report is joined with data to run the print, these sections are printed many times according to their function (and according to
the rules that the report author has set up). For instance, the page header is repeated at the beginning of every page, while the
Detail band is repeated for every elaborated record.
Figure 4-1 on page 46 shows a type page divided into the nine main pre-defined bands to which new groups are added. In
fact, iReport manages a heading band (Group header) and a recapitulation band (Group footer) for every group. Detail, Group
Header and Group Footer bands can then be split further into several bands, so we can have Detail 1, Detail 2, and so on.
A band is always as wide as the usable page width (that is, excluding the right and left margins). However, its height, even if it
is established during the design phase, can vary during the print creation according to the contained elements; it can lengthen
towards the bottom of page in an arbitrary way. This typically occurs when bands contain subreports or textfields that have to
adapt to the content. Generally, the height specified by the user should be considered the minimal height of the band. Not all
bands can stretch dynamically according to the content, in particular the Column Footer, Page Footer and Last Page Footer
bands.
In general, the sum of all band heights (except for the background) always has to be less than or equal to the page height minus
the top and bottom margins. This rule actually is much more complicated, in fact, there are several different cases and options
that must be considered; for example, the Title band may be printed on a different page, the Page Footer and the Last Page
Footer may have different sizes and are never considered together, and so on. For your convenience, the maximum allowed
band size is dynamically calculated at design time by iReport, which prevents the user from setting invalid band heights
(which would lead to a layout verification error at compile time).
46
iReport Ultimate Guide
The following is a list of the pre-defined bands:
Figure 4-1 Pre-defined bands of a document
Title The Title band is the first visible band. It is created only once and can be printed on a
separate page. Regarding the defined dimensions, it is not possible during design time to
exceed the report page height (top and bottom margins are included). If the title is printed
on a separate page, this band height is not included in the calculation of the total sum of all
band heights, which has to be less than or equal to the page height.
Page Header The PageHeader band allows you to define a header at the top of the page. The height
specified during the design phase usually does not change during the creation process
(except for the insertion of vertically re-sizable components, such as textfields that contain
long text and subreports). The page header appears on all printed pages in the same position
defined during the design phase. Title and Summary bands do not include the page header
when printed on a separate page.
Column Header The ColumnHeader band is printed at the beginning of each detail column. (The column
concept will be explained in the “Columns” section later in this chapter.) Usually, labels
containing the column names of the tabular report are inserted in this band.
Report Structure
47
4.1.1 Report Properties
Now that you have seen the individual parts that comprise a report, you can proceed to create a new one. Select New Empty
Report from the File menu, choose a name for the document, and click the Finish button. A new empty report will appear in
the design area of the main window.
Group Header A report can contain zero or more group bands, which permit the collection of detail records
in real groups. A GroupHeader is always accompanied by a GroupFooter (both can be
independently visible or not). Different properties are associated with each group. They
determine its behavior from the graphic point of view. It is possible to always force a group
header on a new page or in a new column and to print this band on all pages if the bands
below it overflow the single page (as a page header, but at group level). It is possible to fix
a minimum height required to print a group header; if it exceeds this height, the Group
Header band will be printed on a new page. Other policies can be set by means of footer
position and the keep together properties. About the Group Header and Group Footer bands,
they can be split in several bands, obtaining an arbitrary set of group headers and a footers.
When split, the bands are enumerated starting from 1. (I will discuss groups in greater detail
later on in this chapter.)
Detail A Detail band corresponds to every record that is read by the data source that feeds the
print. In all probability, most of the print elements will be put here. A report can have
several Detail bands; in other words, the Detail band can be split in a set of sub-bands,
although by default a report has only one Detail band.
Group Footer The GroupFooter band completes a group. Usually it contains fields to view subtotals or
separation graphic elements, such as lines. Like the Detail and the Group Header bandS, the
Group Footer band can be split into several bands.
Column Footer The Column Footer band appears at the end of every column. Its dimensions are not
adjustable at run time (not even if it contained re-sizable elements such as subreports or
textfields with a variable number of text lines).
Page Footer The Page Footer band appears on every page where there is a page header. Like the Column
Footer band, it is not re-sizable at run time.
Last Page Footer If you want to make the footer on the last page of your report different from the other
footers, use the Last Page Footer band. If the band height is 0, it is ignored and the layout
established for the common page will be used also for the last page. This band first
appeared in JasperReports version 0.6.2.
Summary The Summary band allows you to insert fields concerning total calculations, means, or
whatever you want to insert at the end of the report. In other systems, this band is often
named “report footer.”
Background The Background band appeared for the first time in JasperReports version 0.4.6. It was
introduced after requests from many users who wanted to be able to create watermarks and
similar effects (such as a frame around the whole page). It can have a maximum height
equal to the page height and its content will appear on all the pages without being
influenced by the page content defined in the other bands.
No Data The No Data band is an optional report section that is printed only if the data source does
not return any record and the report property When no data type is set to No Data
section. Since this band will be printed instead of all the other bands, the height can be the
same as the report page, excluding margins.
48
iReport Ultimate Guide
The Properties view (on the right side of the main window) shows the properties of the object that is currently selected in the
Report Inspector view (on the left side of the main window) or in the design area (such as a band or an element). When a new
report is created, the property sheet displays the report properties. You can recall the report properties at any time by selecting
the root node in the Report Inspector (showing the report name) or by clicking any area outside the document in the main
window.
The first property is the report name. It is a logical name, independent of the source file’s name, and is used only by the
JasperReports library (for example, as base name for the temporary Java file produced when a report is compiled).
The page dimensions are probably the report’s most important properties. The unit of measurement used by iReport and
JasperReports is the pixel (which has a resolution of 75 dpi, or dots per inch). Table 4-1 lists some standard page formats and
their dimensions in pixels. These are the common formats; a complete list is available in Wikipedia:
By modifying width and height, it is possible to create a report of whatever size you like. The page orientation option,
Landscape or Portrait, in reality is not meaningful, because the page dimensions are characterized by width and height,
independently of the sheet orientation. However, this property can be used by certain report exporters to decide how to orient
the report in a printer.
Figure 4-2 A new empty report in main design window
Table 4-1 Size of a Few Common Page Formats
Format Size in Native Unit of
Measurement
Size in Pixels
(rounded to whole number)
US Letter 8.5 x 11 inches 638 x 825
US Legal 8.5 x 14 inches 638 x 1050
A4 210 × 297 mm 623 x 878
A5 148 × 210 mm 435 x 623
A6 105 × 148 mm 308 x 435
Report Structure
49
The page margin dimensions are set by means of the four fields in the Margins section of the window.
To more easily set the page properties, click Format Page Format to open the Page Format dialog (Figure 4-3).
The Format drop-down contains all the presets listed in Table 4-1. The Unit selector at the bottom of the window allows you
to change the unit of the measures.
4.1.2 Columns
As we have seen (4.1, “Bands,” on page 45), a report is divided into horizontal sections, that is, bands.
The page, which comprises the report, presents portions which are independent of the records coming from the data source
(such as the title section, or the page footers), as well as other sections that are driven by those records (such as the group
headers/footers and the detail). These last portions can be divided into vertical columns in order to optimize the available
space.
Figure 4-3 Page Format dialog
In this context, the concept of “column” can be easily confused with that of “field”. A column is not connected to a
record field; we are just defining the layout of the page, not a table or something tied to the format of the data to print.
This means that if you want to print records having, for instance, ten fields, and you want to create a report that looks
like a table, you don’t need ten report columns, but you’ll have to place the report elements (labels and textfields) in a
single column report in order to get the table effect.
Use columns when you need a layout similar to that of newspapers, where the text rows are presented on several
columns to improve readability and make better use of the space on the page.
50
iReport Ultimate Guide
In the following figures we present two examples. The first shows how to set up a report to use a single column (actually, this
is the default and most common configuration; in this particular case the size of the page is a regular A4).
The values are set in the Report Properties view. The number of columns is 1 and the width is equal to the entire page width,
except for the margins (that’s 535 pixels). Since there is just a single column, the space between columns is not meaningful
and it is set to zero (this property is actually disabled when the column number is 1).
Figure 4-4 Report objects in the outline view
Figure 4-5 Layout of a single column report showing a set of names
Report Structure
51
As you can see in Figure 4-6, most of the page is not used (the figure shows only the first page, but the report is composed of
other pages that look very similar); in fact, each record takes the whole horizontal width of the page. So the idea here is to split
the pages in two columns, so that when the first column reaches the end of the page, we can start to print in this page again in
the second column. Figure 4-7 shows the values used for a two-column report.
In this case, the columns number property is set to 2. iReport will automatically calculate the maximum column width
according to the margins and page width. If you want to increase the space between the columns, just increase the value of the
Column Space property.
Figure 4-6 Result of a report using the single column layout
Figure 4-7 Settings for a two-column report
52
iReport Ultimate Guide
The designer will show the column bounds and the space between the columns.
As we see in Figure 4-9, the page space is now better used.
Figure 4-8 Layout of a two-column report showing a set of names
Figure 4-9 Result of a report using the two-column layout
Report Structure
53
Multiple columns are commonly used for prints of very long lists (for example, the telephone book). The sum of the margins,
column widths and every space between columns, has to be less than or equal to the page width. If this condition is not
verified, the compilation can result in error.
When working with more than one column, you should put elements (fields, images, etc.) inside the first column only. The
other columns are displayed in the designer just for reference, but any element placed here at design time would be treated as
part of the first column (in fact, you are just defining a detail template, so there are no restrictions about placing elements
outside the horizontal band’s bounds, but it would be like putting elements outside the page).
The following picture shows the unsafe areas. They are essentially the margins and all of the page to the right of the first
column.
Of course, the rules about placing elements are applied to the report even if there is only a single column.
4.1.3 Advanced Report Options
Up to now we have seen only basic characteristics concerning the layout. Now we will see some advanced options. Some of
them will be examined thoroughly and explained in every detail in the following chapters, but some of them can be fully
understood and applied in a useful way only after you become familiar with JasperReports.
4.1.3.1 Scriptlet
A scriptlet is a Java class whose methods are executed according to specific events during report creation, such as the
beginning of a new page or the end of a group. For those who are familiar with visual tools such as Microsoft Access or
Microsoft Excel, a scriptlet can be compared with a module in which procedures associated with other events or functions (for
example, the expression of a textfield) are inserted. The scriptlet property identifies only the main scriptlet, but other scriptlets
can be added to the report by using the Report Inspector. I discuss scriptlets at length in Chapter 18.
4.1.3.2 Resource Bundle
The resource bundle is a property used when you want to internationalize a report. A resource bundle is the set of files that
contain the text of the labels, sentences, and expressions used within a report in one defined language. What you set in the
resource bundle property is the resource bundle base name that’s the prefix through which you can find the file with the correct
translation. In order to reconstruct the file name required for a particular language, some language/country initials (for
example, “_it_IT” for Italian-Italy) are added to this prefix, as well as the .properties extension. I will explain
internationalization in greater detail in Chapter 16.
Figure 4-10 Safe area to place report elements (textfields, images, etc.)
54
iReport Ultimate Guide
If a resource is not available, you can specify what to do by choosing an option from the property When resource missing
type. The available options are listed in the following table:
4.1.3.3 Query
The Query property is used to set a query to select data. The language of the query is set through the The language for
the dataset query property. Although the query and its language are presented in the property sheet, it is much more
convenient to edit them using the Query Editor that’s accessible through the tool bar button .
4.1.3.4 Filter Expression
The filter expression is another property that can be edited from the Query Editor. It is a Boolean expression that can use all
the objects of the report (parameters, variables and fields) to determine whether records that are read from the data source
should be used.
Here are some examples of filter expressions:
Filter only records where the field FIRSTNAME starts with the letter “L”:
JavaScript: $F{FIRSTNAME}.substr(0,1) == "L"
Groovy: $F{FIRSTNAME}.startsWith("L")
Filter only records where the length of the field FIRSTNAME is less than 5:
JavaScript: $F{FIRSTNAME}.length < 5
Groovy: $F{FIRSTNAME}.length() < 5
Filter only records where the field FIRSTNAME is the one provided by the parameter NAME:
JavaScript: $F{FIRSTNAME} == $P{NAME}
Groovy: $F{FIRSTNAME} == $P{NAME}
4.1.3.5 Properties
It is possible to define a set of name/value pairs in a report. These pairs are what we call “report properties.” The names and
values are simple strings and they are used for a lot of purposes, including driving special exporter features, overriding
JasperReports default values, and so on. We will see that the same kind of properties can be set for report elements, too.
When editing the properties, the dialog in Figure 4-11 pops up.
Option Description
Null Prints the “Null” string (this is the default option).
Empty Prints nothing.
AllSectionsNoDetails Prints the missing key name.
Error Throws an exception stopping the fill process.
Report Structure
55
Click Add to create a new property. A new window will open (Figure 4-12).
The dialog allows you to specify a property name and value. In the lower part of the window there is a list of special meaning
properties. You can double-click one of them to set the Property name field with that name.
The list of special meaning properties is not exhaustive, but it contains the important properties that have a special meaning
understood by JasperReports. If you scroll the list, you’ll notice that these special properties can be used for a lot of different
tasks, such as specifying particular attributes when the report is exported in a specific format (that is, to avoid pagination when
exporting in XLS), activating special exporter directives (that is, to encrypt the file when exported in PDF), or even specifying
a particular theme to be used with the charts in the document.
Figure 4-11 Properties Dialog
Figure 4-12 Report Properties – Add Property
56
iReport Ultimate Guide
4.1.3.6 Title and Summary on a New Page
The Title on a New Page option specifies that the Title band is to be printed on a new page by forcing a page break at the end
of the Title band. By default this option is not activated. As an example, take a look at Figure 4-13, which shows a simple
report.
Changing the option does not affect the design window. In the editor, the Title band is always drawn above the other bands
(except, when present, the background).
When the report is run, the Title band may go on a separate page, based on the value of the Title on a New Page option.
Figure 4-14 and Figure 4-15 show the same report, the first printed without setting the title on a new page, the second setting
it to true.
Figure 4-13 Title band
Figure 4-14 Default printing of the Title band
Report Structure
57
As you can see in Figure 4-15, when the Title on a New Page option is activated, no other band is printed on the title page, not
even the page header or footer. The page is still counted in the total pages numeration.
4.1.3.7 Summary with Page Header and Footer
The Title on a New Page option is available for the Summary band, as well, the difference being that the Summary band is
printed as the last page. You can print this band on a new page that only contains the Summary band.
By default, the Summary band (which can span one or more pages) does not contain the page header and footer. The option
Summary with Page Header and Footer changes this behavior and forces the header and footer bands (if defined in the
document) to be added when the Summary band is rendered.
4.1.3.8 Floating Column Footer Option
This option allows you to force the printing of the Column Footer band immediately after the last Detail band (or Group
Footer) instead of at the end of the column. This option is used, for example, when you want to create tables using the report
elements (see the JasperReports tables.jrxml example for more details).
4.1.3.9 Print Order
The Print Order option determines how the print data is organized on the page when using multiple columns. The default
setting is Vertical, that is, the records are printed one after the other, passing to a new column only when the previous
column has reached the end of the page (as in a newspaper or phone book).
Figure 4-15 Title band on a new page
58
iReport Ultimate Guide
Horizontal print order prints horizontally across the page, occupying all of the available columns before passing to a new line.
The print orders in shown in the two figures illustrate print order. As you can see, the names are printed in alphabetical order.
In Figure 4-16, they are printed in vertical order (filling in the first column and then passing to the following column), and in
Figure 4-17, they are printed in horizontal order (filling all columns horizontally before passing to the following line).
4.1.3.10 Print without data
When an empty data set is supplied as the print number or the SQL query associated with the report gives back no records, an
empty file is created or a stream of zero byte length is given back. This default behavior can be modified with the Print without
data option; it specifies what to do when there is no data. This table summarizes the option’s possible values and their
meaning.
4.1.3.11 Format Factory Class
A format factory class is a class that implements the interface
net.sf.jasperreports.engine.util.FormatFactory. You can set a custom implementation of the class; it will be
used to define the default format template for numbers and dates.
Figure 4-16 Vertical Print Order Figure 4-17 Horizontal Print Order
Value Description
NoPages This is the default; the final result is an empty buffer.
BlankPage This gives back an empty page.
AllSectionsNo
Details
This gives back a page composed of all the bands except for the Detail band.
No Data
section
Print the No Data band.
Report Structure
59
4.1.3.12 Imports
The imports property is used to add Java-style import directives in the form of a fully referenced class (that is,
java.uitl.List) or with the wild card notation (that is, java.util.*). The purpose is the same as in Java, that is, to
reference classes in expressions without fully referencing them.
4.2 Working with Bands
When creating a new empty report, the default template provides a set of pre-defined bands (background, title, page header,
column header, detail, column footer, page footer and summary). You can see the available bands, as well as other components
of the report, in the Report Inspector.
Figure 4-18 Band properties dialog
60
iReport Ultimate Guide
To add a band to the report, right-click the band in the Report Inspector and select the menu item Add Band from the
menu that appears.
The bands displayed in gray in the Report Inspector (Last Page Footer and No Data) are not present in the report, which
means that if you want to use them, you need to add them.
The pre-defined height of the background band is zero, so you actually don’t see it in the designer but it is present in the
report.
To remove a band from the report, right-click the band in the Report Inspector and select the menu item Delete Band.
You can set the height of unwanted bands to zero, with one exception: the Last Page Footer band. This band is not in the
default template. It automatically replaces the Page Footer band on the last page of the report; you must add it if you want
it in the report.
The properties of the bands can be modified by selecting the band in the Report Inspector or by clicking the free area of
the band in the main designer (not over an element or outside the band bounds).
4.2.1 Band Height
Band Height is the design height of the band. As explained earlier in this chapter, the band height can change during the filling
process. The height of a band in general does not get less than the specified value, even if this is possible because the Remove
Line When Blank option is set in one or more elements in that band and all the conditions to remove the horizontal space taken
by these elements at filling time are verified (the Remove Line When Blank option is explained on page 72 in the next
chapter).When the Band Height property is modified, iReport checks to determine whether the modified value is acceptable
(calculating the available space in the page and taking in consideration options like Title on a new page and Summary on a
new page). If the modified value does not fit the requirements, iReport suggests the possible value range.
4.2.2 Print When Expression
Print When Expression is a Boolean expression (so it must return true or false) that can be used to hide a band and prevent
it from being included in the output report. The expression is evaluated every time the band is referenced in a report. So, for
Figure 4-19 Report Inspector in main design window
Report Inspector
Report Structure
61
example, in a report page the title band is evaluated only once, while for the page header it is evaluated every time a new page
is produced and for the Detail band it is evaluated every time a new record is processed.
As in all the expressions, you are free to use all the report objects available (fields, parameters and variables).
4.2.3 Split Allowed and Split Type
The Split Allowed option is deprecated, and its use has been replaced by the Split Type property. It is used to control what
to do when a band cannot be fully rendered in the remaining space on the page. Keeping in mind that bands can grow
dynamically during the filling process, it is easy for a band to expand so much that it no longer fits on the current page or
column.
Here is a reference to the options for Split Type (from the JasperReports XSD schema):
4.3 Summary
At this point, you should understand the structure of a page and how it is divided into several bands. You should also
understand the conditional nature of bands, as well as how iReport evaluates whether and how to include a band in a report
page. In the bands we will add the content to be printed.
In the next chapter, we will see how to use the group header and the group footer bands, and what other options can be set to
place band groups in a new column or on a new page.
Option Description
Stretch The band is allowed to split, but not within its declared height.
This type allows a band to be split only if the band is stretched and only if the band expands
beyond the declared band height. If we have a declared band height of 100 pixels, the band
cannot break within the first 100 pixels. Any break must occur beyond 100. For instance, if the
band has a total of 110 pixels, a break can only occur in the final 10 pixels.
Prevent Prevents the band from splitting on the first break attempt. On subsequent pages, the band is
allowed to split any number of times.
If there is not enough space on the current page to render the band, the entire band is rendered
on the next page. If the available space on the new page is still not enough, the remaining band
can be split any number of times.
Immediate The band is allowed to split anywhere, as early as needed, but not before at least one element is
printed on the current page.
62
iReport Ultimate Guide
Report Elements
63
CHAPTER 5REPORT ELEMENTS
In this chapter, I will explain the main objects that can be inserted in a report and discuss their characteristics.
The basic unit of reports is the element. By “element,” I mean a graphical object, such as a text string or a rectangle. Unlike in
a word processing program, in iReport the concept of line or paragraph does not exist; everything is created by means of
elements, which can contain text, create tables when they are opportunely aligned, and so on. This approach follows the model
used by the majority of report authoring tools.
Nine basic elements are offered by the JasperReports library:
Line
Rectangle
Ellipse
Static text
Textfield (or simply Field)
Image
Frame
Subreport
Crosstab
Chart
Break
Through a combination of these elements, it is possible to produce every kind of report. JasperReports also allows developers
to implement their own generic elements and custom components for which it is possible to add support in iReport to create a
proper plug-in.
All elements have common properties, such as height, width, position, and the band to which they belong. Other properties are
specific to the type of element (for example, font or, in the case of a rectangle, thickness of the border). There are several
types; graphic elements are used to create shapes and display images (they are line, rectangle, ellipse, image); text elements are
used to print text strings such as labels or fields (they are static text and textfield); the frame element is used to group a set of
elements and optionally draw a border around them. Subreports, charts and crosstabs are more complex elements, so I will
touch briefly on them later in the this chapter and discuss them in more detail in separate chapters. Finally, there is a special
element used to insert a fixed-in-place page or column break.
Elements are inserted into bands, and every element is associated indissolubly with its band. If an element is not completely
contained within the band that it is part of, the report compiler will return a message that informs you about the position of the
element; the report will be compiled despite such an error, and in the worst case, the out-of-band element will not be printed.
This chapter has the following sections:
Working with Elements
64
iReport Ultimate Guide
Working with Images
Working with Text
Other Elements
Adding Custom Components and Generic Elements
5.1 Working with Elements
The elements are presented in a palette, usually located in the top right portion of the main window (see Figure 5-1).
To insert an element in a report, drag the element from the palette into a report band. The new element will be created with a
standard size and will appear in the Report Inspector. To select the element, click it in the designer or in the Report Inspector.
You can adjust the element position by dragging it; to modify its size, select it then drag a corner of the orange selection frame.
When dragging or resizing an element, iReport suggests places to align it, based on the elements already in the design pane,
the band bounds, and (if present) guidelines.
To obtain greater precision in the movement, use the arrows keys to move the element one pixel at a time; similarly, using the
arrow keys while pressing the Shift key moves the element 10 pixels.
If you need reference points to position and align elements in the page, you can turn on the grid in the design pane by selecting
the menu item View Report Designer Show Grid.
To force the elements to snap to the grid, select View Report Designer Snap to Grid.
Figure 5-1 Tools palette
Figure 5-2 Suggested alignment with other elements
Report Elements
65
Guidelines are also useful to position your elements in the report. With the guidelines’ magnetic effect, it is easy to place the
elements in the right position. To create a guideline, just click a ruler (vertical or horizontal) and drag the guideline to the
wanted position (see Figure 5-3). By default, rulers use inches as their unit of measure. In the Options panel (Tools >
Options), you can set a different unit.
You can drag and change the position of a guideline at any time; this will have no effect on the element’s position.
To remove a guideline, drag it to the top/left corner of the design pane.
The top and left values that define the element’s position are always relative to the parent band, or, to be more accurate, to the
parent container, which is usually a band but could be a frame element.
If you want to move an element from its initial band to another band or a frame, or vice versa, drag the element node from the
Report Inspector to the new band (or frame) node, as shown in Figure 5-4.
Figure 5-3 Guidelines
Figure 5-4 Moving an element from one band to another
66
iReport Ultimate Guide
In the designer window, you can drag an element from one band to another band, but the element’s parent band will not
change. Although we said that an element must be contained in its band, there are several exceptions to this rule. iReport
allows you to move an element anywhere in the report without changing or updating the parent band.
As general rule, an element must remain in its parent band; it should not be moved even partially out of the band. A design
error will be displayed in the Report Problems view and the report will not run. In Figure 5-5 we have a text element which
has the Title as parent band. Since the element height spans the Page Header band below the Title band, a warning about the
invalid element position appears in the Report Problems view.
You can use the property sheet to edit an element properties; it is usually located on the right side of the designer window. The
property sheet is not used only for elements; it can be used to edit the properties of all the components that make up the report,
including the page format, the band options, parameters, variables and fields options, and so on. When something is selected in
the designer or in the Report Inspector view, the property sheet shows the options for the selected object.
Figure 5-5 Element not correctly positioned
Report Elements
67
It is possible to select several elements at the same time by drawing a rectangle around the elements with the arrow tool.
Depending on the direction in which the rectangle is drawn, elements can be selected only if fully contained in the selected
area or partially selected.
Alternatively, it is possible to select more than one element at the same time by holding down the Shift key and clicking all the
desired elements.
Figure 5-6 Element not correctly positioned
Figure 5-7 Selection left to right Figure 5-8 Only elements fully contained in
the selected area are selected
68
iReport Ultimate Guide
Specifying a value for a particular property applies that value to all selected elements. However, if two or more elements are
selected, only their common properties are displayed in the property sheet. If the values of the properties are different, the
value fields will be blank (usually the field is shown empty). To edit properties unique to one element, select only that element.
5.1.1 Formatting Tools
To better organize the elements in the designer window, a comprehensive set of tools is provided. To access the formatting
tools view, select the Window Formatting tools. The tools view will appear. Each tool is enabled only when the selection
matches its minimum requirements (single or multiple selection).
Table 5-1 lists the available tools, specifying what kind of selection each tool requires (single or multiple selection) and
briefly explaining what each tool does.
Figure 5-9 Formatting Tools view
Table 5-1 Formatting Tools
Icon Tool Description Multiple
select?
Align left Aligns the left sides to that of the primary element.
Align right Aligns the right sides to that of the primary element.
Align top Aligns the top sides (or the upper part) to that of the primary element.
Align bottom Aligns the bottom sides to that of the primary element.
Align vertical axis Centers horizontally the selected elements according to the primary
element.
Report Elements
69
Align horizontal axis Centers vertically the selected elements according to the primary
element.
Align to band top Sets the top value at 0.
Align to band bottom Puts the elements in the position at the bottom as much as possible
according to the band to which it belongs.
Same width Sets the selected elements width equal to that of the primary element.
Same width (max) Sets the selected elements width equal to that of the widest element.
Same width (min) Sets the selected elements width equal to that of the most narrow
element.
Same height Sets the selected elements height equal to that of the primary element.
Same height (max) Sets the selected elements height equal to that of the highest element.
Same height (min) Sets the selected elements height equal to that of the lowest element.
Same size Sets the selected elements dimension to that of the primary element
Center horizontally
(band-based)
Puts horizontally the selected elements in the center of the band
Center vertically
(band-based)
Puts vertically the selected elements in the center of the band
Center in band Puts the elements in the center of the band
Center in background Puts the elements in the center of the page in the background
Join sides left Joins horizontally the elements by moving them to the left
Join sides right Joins horizontally the elements by moving them towards right
Horiz. Space Make
equal
Distributes equally the horizontal space among elements
Horiz. Space
Increase
Increases by 5 pixels the horizontal space among elements by moving
them to the right
Horiz. Space
Decrease
Decreases by 5 pixels the horizontal space among elements by moving
them to the left
Horiz. Space
Remove
Removes the horizontal space among elements by moving them to the
left
Vert. Space Make
equal
Distributes equally the horizontal space among elements
Vert. Space
Increase
Increases by 5 pixels the horizontal space among elements (by moving
them towards right)
Vert. Space
Decrease
Decreases by 5 pixels the horizontal space among elements by moving
them to the left
Table 5-1 Formatting Tools, continued
Icon Tool Description Multiple
select?
70
iReport Ultimate Guide
5.1.2 Managing Elements with the Report Inspector
The Report Inspector shows the complete report structure. The root node represents the page; you can select it to modify all the
general report properties, as we have seen in the previous chapter. The following nodes are used for the style, the parameters,
the fields and the variables and other report objects if present (like subdatasets).
After these nodes there are the bands. Each band contains the elements. Container elements (like frames) can have other
elements represented as subnodes. The order of the elements in the Inspector is important because it is the z-order (the position
from the depth point of view). In other words, if an element precedes other elements in the Inspector view, it will be printed
before them. If an element overlaps some predecessors, it will cover them.
Please note that some exporters (like the HTML exporter) do not support overlapping elements, so they are skipped during the
rendering; at other times you can have two or more overlapped elements and print only one of them, using the print when
condition; this is a simple trick to print different content-based on a condition.
To change the z-order, you can move the elements by dragging them in the Inspector, or you can use the Move Down and
Move Up menu items. Remember that elements on top of the list are printed first, so to bring an element to front, you need to
move it down in the list.
All the elements can be copied and pasted, except for charts and crosstabs. When an element is pasted, it keeps the top/left
coordinates used in its previous container (a band, a cell or a frame). If the new container is smaller than the previous one, you
may need to adjust the element position since it could be outside the new container’s bounds.
The Report Inspector allows you to select elements inside the report even if those elements are not visible in the designer or
even if they are hard to select due to the complexity of the report.
5.1.3 Basic Element Attributes
All the elements have a set of common properties, or attributes; they are presented in the element properties view (as shown
earlier in Figure 5-1). These attributes concern information about element positioning on the page. The following table
describes the available attributes.
Figure 5-10 shows how iReport positions an element relative to the band to which the element belongs (or, more broadly, to
its container). The band width is always equal to the document page width minus the left and right margins; its height can
change depending on the type of band and the contained elements.
Vert. Space
Remove
Removes the horizontal space among elements by moving them to the
left
Adapt to parent Increases the size of the element to fit the size of its container (a band,
a cell or a frame)
Adapt to parent width Increases the width of the element to fit the width of its container (a
band, a cell or a frame)
Adapt to parent height Increases the height of the element to fit the height of its container (a
band, a cell or a frame)
Organize as a table Aligns the selected elements by their tops and makes equal the
horizontal space between them
Table 5-1 Formatting Tools, continued
Icon Tool Description Multiple
select?
Report Elements
71
Figure 5-10 Element positioning
Table 5-2 Element positioning properties
Top This is the distance of the top-left corner of the element from the top of the container the
element belongs.
Left This is the distance of the top-right corner of the element from the left margin of the
container.
Width This is the element width.
Height This is the element height; in reality, this indicates a minimum value that can increase
during the print creation according to the value of the other attributes.
* Coordinates and dimensions are always expressed in pixels in relation to a 72-pixel-per-inch resolution.
Table 5-3 Other element properties
Foreground This is the color with which the text elements are printed and the lines and the
element corners are drawn.
Background This is the color with which the element background is filled. Since, by default, some
elements are transparent, remember to make the element opaque.
Opaque This option controls whether the element background is transparent or not; the
transparency involves only the parts that should be filled with the background.
Not all export formats support the transparency attribute.
Style If the user has defined one or more styles in the report, it is possible to apply a style to
the element by selecting it from the list.
Key This is the element name, which has to be unique in the report (iReport proposes it
automatically), and it is used by the programs that need to modify the field properties
at run time.
Position type This option determines how the top coordinates have to be considered if the band
changes its height during the filling process. The three possible values are as follows:
FixRelativeToTop This is the pre-defined position type; the coordinate values never change.
Float The element is progressively pushed toward the bottom by the previous elements that
increase their height.
FixRelativeToBottom The distance of the element from the bottom of the band remains constant; usually
this is used for lines that separate records.
72
iReport Ultimate Guide
5.1.4 Element Custom Properties
For each element it is possible to define a set of custom properties; each property is a pair key/value where both key and value
are simple text strings. The value can be generated using an expression (that will have to return a string, of course).
Element custom properties are set by modifying the Properties expressions attribute in the property sheet displayed
when the element is selected (see Figure 5-11).
Stretch type This attribute defines how to calculate the element height during the print elaboration;
the three possible values are as follows:
NoStretch This is the pre-defined stretch type, and it dictates that the element height should be
kept equal.
RelativeToBandHeight The element height is increased proportionally to the increasing size of the band; this
is useful for vertical lines that simulate table borders.
RelativeToTallestObject The element modifies its height according to the deformation of the nearest element:
this option is also used with the element group, which is an element group mechanism
not managed by iReport.
Print repeated values This option determines whether to print the element when its value is equal to that
which is used in the previous record.
Remove line when blank This option takes away the vertical space occupied by an object if the object is not
visible; the element visibility is determined by the value of the expression contained in
the Print when expression attribute or in case of textfields by the Blank when
null attribute. Think of the page as a grid where the elements are placed, with a line
being the space the element occupies. The figure below highlights the element A line;
in order to remove this line, all the elements that share a portion of the line have to be
null (that is, they will not be printed).
Print in first whole
band
This option ensures that an element is printed in the next page or column if the band
overflows the page or column; this type of guarantee is useful when the Print
repeated values attribute is enabled.
Print when detail
overflows
This option prints the element in the following page or column, if the entire band is not
printable in the present page or column.
Print when group changes In this combo box, all report groups are presented. If one of them is selected, the
element will be printed only when the expression associated with the group changes,
that is, when a new break of the selected group is created.
Print when expression This is an expression like those described in Chapter 3, and it must return a Boolean
object. Besides being associated with elements, this expression is associated with the
bands, as well. If the expression returns true, the element is hidden. An empty
expression or a null value implicitly identifies an expression like new
Boolean(true), which will print the element unconditionally.
Properties expressions These are a set of key/value pairs that can be defined for each element.
Table 5-3 Other element properties, continued
Report Elements
73
Custom element properties can be used for many purposes, such as specifying special behavior for an element when it is
exported in a particular format, or setting how characters should be treated in a textfield or, again, setting special tags like
those required by Standard 508 to define the structure of a document.
When a property is created, the property dialog suggests some of the most important common property keys with a short
description of the property meaning.
To use an expression, check the Use an expression check box.The text area will become an expression area and the button to
open the expression editor will appear.
5.1.5 Graphic Elements
Graphic elements are drawing objects such as line and rectangle; they do not show data generally, but they are used to make
prints more readable and agreeable from an aesthetic point of view. All elements have the pen and the fill properties.
Figure 5-11 Custom element properties
Figure 5-12 Custom property dialog
74
iReport Ultimate Guide
pen is used to draw a shape (or just the borders of the element in case of images). This property is edited with the Pen dialog
(see Figure 5-13).
It is possible to set a particular line width (a zero line width means that no lines will be painted) and choose between 4 different
styles: normal, dashed, dotted and double.
By default, the color used to paint the lines is the element foreground color, but it is possible to override that value by
specifying a different value. To reset the color the default value you need to reset the whole pen right clicking the Pen item in
the property sheet and selecting Restore Default Value.
The default values for the pen (like for many other common element properties) depend on the specific element. Lines,
rectangles and ellipses have a default width of 1 pixel, while for images the default line width is zero.
The Fill property has a single possible value: Solid.
5.1.5.1 Line
In JasperReports, a line is defined by a rectangle for which the line represents the diagonal (see Figure 5-14).
The line is drawn using the pen settings. If they are not set, the foreground color is used as the default color and a normal 1-
pixel-width line is used as the line style.
The only specific property of a line is the Line direction, used to indicate which of the two rectangle diagonals represents
the line; the possible values are Top Down and Bottom Up.
Figure 5-13 Pen Definition
Figure 5-14 Line element of type top-down
Report Elements
75
5.1.5.2 Rectangle
The rectangle element is usually used to draw frames around other elements (even if it is preferable to use a frame element for
this specific purpose in order to avoid overlapping elements). Similarly to the line element, the rectangle border is drawn using
the pen settings. If they are not set, the Foreground setting is used as color (which is black by default) and a normal 1-pixel-
width line is used as line style. The background is filled with the color specified with the Background setting if the element has
not been defined as transparent.
In JasperReports, it is possible to have a rectangle with rounded corners (see Figure 5-15). The rounded corners are defined by
means of the Radius attribute, which represents the curvature radius of the corners, expressed in pixels.
5.1.5.3 Ellipse
The ellipse is the only element that has no attributes specific to it. The ellipse is drawn in a rectangle that defines the maximum
height and width (see Figure 5-16). The border is drawn using the pen settings. If they are not set, the Foreground is used as
color (which is black by default) and a normal 1-pixel-width line is used as line style. The background is filled with the
Background color setting if the element has not been defined as transparent.
Figure 5-15 Rectangle element with radius set to 20
Figure 5-16 Ellipse element and its rectangular boundary
76
iReport Ultimate Guide
5.2 Working with Images
An image is the most complex of the graphic elements. It can be used to insert raster images (such as GIF, PNG and JPEG
images) in the report, but it can be also used as a canvas object to render, for example, a Swing component, or to leverage
some custom rendering code.
When you drag an image element from the Palette into the Designer, iReport pops up a file chooser dialog. This is the most
convenient way to specify an image to use in the report. iReport will not save or store the selected image anywhere, it will just
use the file location, translating the absolute path of the selected image into an expression to locate the file when the report is
executed. The expression is then set as the value for the Image Expression property. Here is a sample expression:
"C:\\Documents and Settings\\gtoffoli\\Desktop\\splashscreen.png"
As you can see, this is a Java (or Groovy or JavaScript) expression, not just the value of a file path. It starts and ends with
double quotes, and the back slash character (\) is escaped with another back slash (\\).
The Image Expression Class defines what kind of object is returned by the Image Expression. In this case, it is of the type
java.lang.String, but there are several other options.
Table 5-4 summarizes the values that the Image Expression Class can adopt and describes how the Image Expression
result is interpreted and used.
Figure 5-17 Image element
Table 5-4 Image Expression Class Values
Type Interpretation
java.lang.String A string is interpreted like a file name. JasperReports will try to interpret the string like
an absolute path. If no file is found, it will try to load a resource from the classpath with
the specified name. Correct expressions are:
“c:\\devel\\ireport\\myImage.jpg”
“com/mycompany/resources/icons/logo.gif”
java.io.File Specifies a file object to load as an image.
A correct expression could be:
new java.io.File(“c:\\myImage.jpg”)
Report Elements
77
You are free to add an image by explicitly defining the full absolute path of the image file in your expression. This is an easy
way to add an image to the report, but, overall, it has a big impact on the report’s portability, since the file may not be found on
another machine (for instance, after deploying the report on a web server or running the report on a different computer).
There are two best practices here:
Parametrize the image expression containing the folder where your images resides (possibly using a parameter with a
default value), then composing the expression like this:
$P{MY_IMAGES_DIRECTORY} + “myImage.png”
At run time in a hypothetical application, the value for the parameter MY_IMAGES_DIRECTORY can be set by the
application itself. If a value for the parameter is not provided, we can still return a default value (we’ll see how to create a
parameter and set a default value in the next chapter). The advantage of this solution is that the location of the directory
where the images reside is not defined discretely within the report, but can be provided dynamically.
The second option is to use the classpath. The classpath defines the directories and JAR file locations where a Java
application like JasperReports looks for classes and resources. If the application uses the Java Virtual Machine, it is
usually easy to add directories to the classpath.
In iReport, the classpath can be extended from the Options dialog (Window > Options > iReport > Classpath). When an
image is in the classpath, the only required information JasperReports needs in order to find and render the image is the
resource name (that is a kind of path that is relative to the classpath). By default, when executing a report, iReport adds the
directory in which the report resides to the classpath. Suppose you have a report in a certain directory, let’s say
c:\test\myReport.jrxml, and in the same directory you have an image named myImage.png. To use it in the report, you can
set Image Expression to myImage.png. Since the report’s directory is in the classpath, the image will be found
automatically.
This process is still valid if the image resides in a subdirectory of the classpath. You will have to specify the subdirectory
path, using a Unix-style path notation. For example, if your image resides in c:\test\images rather than c:\test, the resource
is found with the expression /images/myImage.png.
This method of resolving resource locations is applied in many other parts of JasperReports, as well (for example, in
locating a subreport Jasper file, a resource bundle, a scriptlet class, and so on).
java.net.URL Specifies the java.net.URL object. It is useful when you have to export the report in
HTML format. A correct expression could be:
new java.net.URL(“http://127.0.0.1/test.jpg”)
java.io.InputStr
eam
Specifies a java.io.InputStream object which is ready for reading. In this case,
we do not consider that the image exists and that it is in a file. In particular, we could
read the image from a database and return the inputStream for reading. A correct
expression could be:
MyUtil.getInputStream(${MyField})
java.awt.Image Specifies a java.awt.Image object; it is probably the simplest object to return when
an image has to be created dynamically. A correct expression could be:
MyUtil.createImage()
JRRenderable Specifies an object that uses the
net.sf.jasperreports.engine.JRRenderable interface.
Table 5-4 Image Expression Class Values, continued
Type Interpretation
78
iReport Ultimate Guide
Let’s take a look at the remaining options:
Table 5-5 Image Expression Class Options
Option Explanation
Scale Image Defines how the image has to adapt to the element dimension; the possible values are three:
Clip The image dimension is not changed
FillFrame The image is adapted to the element
dimension (becoming deformed)
RetainShape The image is adapted to the element
dimension by keeping the original
proportions
On error type Defines what to do if the image loading fails:
Error A java exception stopping the filling process
Blank The image is not printed, and a blank space will be placed in the report instead
Icon An icon is printed instead of the original image
Is Lazy Avoids the loading of the image at fill time; the image will be loaded when the report is
exported. Useful when an image is loaded from a URL.
Using cache Allows to keep the image into the memory in order to use it again if the element is printed
newly; the image is kept in cache only if the Image Expression Class is set to
java.lang.String.
Vertical alignment Defines the image vertical alignment according to the element area; the possible values are:
Top Aligned at the top edge of the element area
Middle Image is centered vertically according to the element area
Bottom Aligned at the bottom edge of the element area
Horizontal alignment Defines the image horizontal alignment according to the element area; the possible values
are:
Left Aligned to the left edge of the element area
Center Image is centered horizontally according to the element area
Right Aligned to the right edge of the element area
Report Elements
79
5.2.1 Padding and Borders
For the image element (and for the text elements) it is possible to visualize a frame or to define a particular padding for the
four sides. It is the space between the element border and its content. Border and padding are specified by right-clicking the
element (or the element node in the Inspector view) and selecting the menu item Padding and Borders. This will open the
dialog box shown in Figure 5-18.
Evaluation time Defines the time at which the Image Expression has to be processed. The evaluation of
an expression can be done when the report engine “encounters” the element during the
creation of the report (evaluation time “now”) or it can be postponed.For example, it might
be postponed because the image depends on calculations that have not yet been completed.
The evaluation time is applied to the evaluation of many expressions (including textfields
and variables). An in-depth explanation of the evaluation time is available in the next
chapter. The possible values for the evaluation time are:
Now Evaluate the expression immediately
Report Evaluate the expression at the end of the report
Page Evaluate the expression at the end of the page
Column Evaluate the expression at the end of this column
Group Evaluate the expression of the group which is specified in Evaluation group
Band Evaluate this expression after the evaluation of the current band (used to evaluate
expressions that deal with subreport return values)
Evaluation group See the preceding Group value description for the Evaluation time setting.
Figure 5-18 Padding and borders
Table 5-5 Image Expression Class Options, continued
Option Explanation
80
iReport Ultimate Guide
As always, all the measurements must be set in pixels.
The four sides of the border can be edited individually by selecting them in the preview frame. When no sides are selected,
changes are applied to all of them.
Image elements can have a hyperlink. Not all the export formats support them, but they have been verified in HTML, PDF and
XLS. To define a hyperlink, right-click the image element and select the Hyperlink menu item. The hyperlink definition dialog
will appear. We will explain in depth how to define an hyperlink using this dialog later in the chapter.
5.2.2 Loading an Image from the Database (BLOB Field)
If you need to print images that are stored in a database (that is, using a BLOB column) what you need to do is assign the field
that will get the BLOB value the type java.awt.Image (report fields will be explained in the next chapter). Create an image
element by dragging the image element tool from the palette into the designer (that is, into the Detail band), click Cancel when
the file chooser prompts. Then, in the image element properties sheet, change the Image Expression Class to
java.awt.Image and set as Image Expression the field object (that is, $F{MyImageField} ).
5.2.3 Creating an Image Dynamically
To create an image dynamically requires some Java knowledge. Here we will show the best solution to modify or create an
image to be printed in a report.
There are several ways to create an image dynamically in JasperReports. The first option is to write a class that produces a
java.awt.Image object and call a method of this class in the Image Expression of the image element. The expression would
look like:
MyImageGenerator.generateImage()
where MyImageGenerator is a class with the static method generateImage() that returns the java.awt.Image object.
The problem with this solution is that, since the image created would be a raster image with a specific with and height, in the
final result there could be there a loss of quality, especially when the document is zoomed in, or when the final output is a PDF
file.
Generally speaking, the best format of an image that must be rendered in a document is an SVG, which provides high image
quality regardless of original capture resolution. In order to ease the generation of a custom image, JasperReports provides an
interface called JRRenderable that a developer can implement to get the best rendering result. A convenient class to initial
use of this interface is JRAbstractSVGRenderable. The only method to implement here is:
public void render(Graphics2D g2d, Rectangle2D rect)
which is where you should put your code to render the image. Code Example 5-1 shows a simple implementation of a
JRAbstractSVGRenderable to paint the outline text “JasperReports!!” inside an image element using a gradient
background.
Code Example 5-1 Dynamic image generation
package com.jaspersoft.ireport.samples;
import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.font.FontRenderContext;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;import
net.sf.jasperreports.engine.JRAbstractSvgRenderer;
import net.sf.jasperreports.engine.JRException;
Report Elements
81
The final result is shown in Figure 5-19. The CustomImageRenderer class implements the interface
JRAbstractSvgRenderer. The renderer just fills the background with the fillRect method using a Gradient Paint, creates
a shape out of the “JasperReports!!!” text, and renders the shape centered with a translation.
/**
*
* @author gtoffoli
*/
public class CustomImageRenderer extends JRAbstractSvgRenderer {
public void render(Graphics2D g2d, Rectangle2D rect) throws JRException {
// Save the Graphics2D affine transform
AffineTransform savedTrans = g2d.getTransform();
Font savedFont = g2d.getFont();
// Paint a nice background...
g2d.setPaint(new GradientPaint(0,0, Color.ORANGE,
0,(int)rect.getHeight(), Color.PINK));
g2d.fillRect(0,0 , (int)rect.getWidth(), (int)rect.getHeight());
Font myfont = new Font("Arial Black", Font.PLAIN, 50);
g2d.setFont(myfont);
FontRenderContext frc = g2d.getFontRenderContext();
String text = new String("JasperReports!!!");
TextLayout textLayout = new TextLayout(text, myfont, frc);
Shape outline = textLayout.getOutline(null);
Rectangle r = outline.getBounds();
// Translate the graphic to center the text
g2d.translate(
(rect.getWidth()/2)-(r.width/2),
rect.getHeight()/2+(r.height/2));
g2d.setColor(Color.BLACK);
g2d.draw(outline);
// Restore the Graphics2D affine transform
g2d.setFont(savedFont);
g2d.setTransform( savedTrans );
}
}
Code Example 5-1 Dynamic image generation, continued
82
iReport Ultimate Guide
What we did is to set the Image Element Expression to:
new com.jaspersoft.ireport.samples.CustomImageRenderer()
and the Image Expression Class to net.sf.jasperreports.engine.JRRenderable. We have not passed any
argument to our implementation class, but this is possible, allowing the final user to pass to the renderer extra information to
produce the image.
With a similar approach it is possible to modify an image (rotate, transform and so on), add a watermark to an image or even
insert into the report a Swing component.
Code Example 5-2 shows how to print a JTable. The code is not much different from what we have seen in the previous
sample; the idea is to force the component to paint itself into the provided Graphics2D. The result is incredibly good and there
is no loss of quality when using the internal JasperReports preview component (see Figure 5-20) or when exporting to PDF.
.
Figure 5-19 An image element rendered using a custom JRRenderable object
Code Example 5-2 Printing a JTable
package com.jaspersoft.ireport.samples;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import net.sf.jasperreports.engine.JRAbstractSvgRenderer;
import net.sf.jasperreports.engine.JRException;
/**
*
* @author gtoffoli
*/
public class SwingComponentRenderer extends JRAbstractSvgRenderer {
public void render(Graphics2D g2d, Rectangle2D rect) throws JRException {
/ Save the Graphics2D affine transform
AffineTransform trans = g2d.getTransform();
Report Elements
83
5.3 Working with Text
There are two elements specifically designed to display text in a report: static text and textfield. The first is used for creating
labels or more in general to print static text set at design time and not supposed to change when the report is generated. That
said, in some cases you will still use a textfield to print labels too, since the nature of the static text elements prevents the
ability to display text dynamically translated in different languages when the report is executed with a specific locale and it is
configured to use a resource bundle leveraging the JasperReports internationalization capabilities.
// Create a simple table model
DefaultTableModel model = new DefaultTableModel(
new Object[][] {
{"Mercury","NO"},
{"Venus","NO"},
{"Earth","YES"},
{"Mars","YES"},
{"Jupiter","YES"},
{"Saturn","YES"},
{"Uranus","YES"},
{"Neptune","YES"},
{"Pluto","YES"}},
new String[]{"Planet","Has satellites"});
// Create the table using the model
JTable table = new JTable(model);
// Set the column size
table.getColumn("Planet").setWidth(100);
table.getColumn("Has satellites").setWidth(100);
// Resize the table to accommodate the new size
table.setSize(table.getPreferredSize());
// Get the header and set the size to the preferred size
JTableHeader tableHeader = table.getTableHeader();
tableHeader.setSize(tableHeader.getPreferredSize());
// Paint the header
tableHeader.paint(g2d);
// Paint the table
g2d.translate(0, tableHeader.getHeight());
table.paint(g2d);
// Restore the Graphics2D affine transform
g2d.setTransform( trans );
}
}
Code Example 5-2 Printing a JTable, continued
84
iReport Ultimate Guide
A textfield acts in a way similar to a static text string, but the content (the text to print) is provided using an expression (that
actually could be a simple static text string itself). That expression can return several kinds of value types, not just String,
allowing the user to specify a pattern to format that value (this can be applied in example on numeric values and dates). Since
the text specified dynamically can have an arbitrary length, a textfield provides several options about how the text must be
treated regarding alignment, position, line breaks and so on. Optionally, the textfield is able to grow vertically to fit the content
when required. By default text elements are transparent with no border and with a black foreground color. All these properties
can be modified using the common portion of the element property sheet and using the pop-up menu Padding And Borders.
Textfields support hyperlinks too, refer the section about how to define them later in this chapter for more information.
Static texts and textfields share a set of common properties to define text alignment and fonts. Let’s take a look at these
options:
Figure 5-20 A JTable printed inside an image element
Font name This is the name of the font, the list presents all the fonts found in the system.
Like often happens with text documents, you may see fonts that are could not
be found on other machines, so choose your font name carefully to keep the
maximum compatibility. When exporting in PDF, this property is ignored, since
PDF requires and the PDF font name is used instead. More information about
the correct use of the fonts are provided in the “Fonts” chapter.
Font size This is the size of the font. Only integer numbers are allowed, meaning that you
cannot define that is, a size of 10.5.
Bold
Italic
Set the text style to bold and italic. These two properties does not work when
the report is exported in PDF. In that case you need to specify a proper PDF
font.
Underline
Strikethrough
Set the text style to underline and strikethrough.
Report Elements
85
PDF font name
PDF encoding
PDF embedded
These flags are explained in 8.3, “Using the Font Extensions,” on page 127.
Horizontal align This is the horizontal alignment of the text according to the element.
Vertical align This is the vertical alignment of the text according to the element.
Rotation This specifies how the text has to be printed. The possible values are as
follows:
None The text is printed normally from
left to right and from top to
bottom.
Left The text is rotated of 90 degrees
counterclockwise; it is printed
from bottom to top, and the
horizontal and vertical
alignments follow the text
rotation (for example, the bottom
vertical alignment will print the
text along the right side of the
rectangle that delimits the
element area)
Right The text is rotated of 90 degrees
clockwise from top to bottom,
and the horizontal and vertical
alignments are set according to
the text rotation.
UpsideDown The text is rotated 180 degrees
clockwise.
Line spacing This is the interline (spacing between lines) value. The possible values are as
follows:
Single Single interline (pre-defined value)
1.5 Interline of one line and a half
Double Double interline
Markup This attribute allows you to format the text using a specific markup language.
This is extremely useful when you have to print some text that is pre-formatted,
that is, in HTML or RTF. Simple HTML style tags (like <b> for bold and <i> for
Italic) can be used in example to highlight a particular chunk of the text. The
possible values are as follows:
86
iReport Ultimate Guide
None No processing on the text is performed, and the text is printed exactly like it is
provided.
Styled This markup is capable to format the text using a set of HTML-like tags and it is
pretty popular in the Java environments. It allows to set a specific font for
chunks of text, color, background, style and so on. It’s often good enough to
format the text programmatically.
HTML If you want to print some HTML text into your report, this is what you need, but
it’s primary use is to format text, so don’t expect to be able to print tables or add
images.
RTF Setting the markup to this value, the content will be interpreted as RTF code.
RTF is a popular document format stored in pure text. The little piece of text
saying “this is a text formatted in RTF” in Illustration 19 has been generated
using the string:
{\rtf1\ansi\ansicpg1252\deff0\deflang1033{\fonttbl{\f0\fswiss\fcharset0
Arial;}{\f1\fnil\fprq2\fcharset0 Swift;}}
{\*\generator Msftedit 5.41.15.1507;}\viewkind4\uc1\pard\f0\fs20 This is a
text \f1\fs52 formatted \f0\fs20 in RTF\par
}
The string is actually an RTF file created using a simple word processor.
Report font This is the name of a preset font, from which will be taken all the character
properties. This attribute is deprecated and it is there only for compatibility
reason (that’s why it the label is lined out. In order to define a particular style of
text to use all over your document, use a style (explained in Chapter 8).
Figure 5-21 Text formatted with several markups and styles
Report Elements
87
For your convenience, the most used text properties can be modified using the text tool bar (see Figure 5-22) that is displayed
when a text element is selected.
The first two buttons on the left of the font size selector can be used to increase and decrease the font size.
5.3.1 Static Text
The static text element is used to show non-dynamic text in reports (see Figure 5-23). The only parameter that distinguishes
this element from a generic text element is the Text property, where the text to view is specified: it is normal text, not an
expression, and so it is not necessary to enclose it in double quotes in order to respect the conventions of Java, Groovy, or
JavaScript syntax.
5.3.2 Textfields
A textfield allows you to print an arbitrary section of text (or a number or a date) created using an expression. The simplest
case of use of a textfield is to print a constant string (java.lang.String) created using an expression like this:
"This is a text"
A textfield that prints a constant value like the one returned by this expression can be easily replaced by a static field; actually,
the use of an expression to define the content of a textfield provides a high level of control on the generated text (even if it’s
just constant text). A common case is when labels have to be internationalized and loaded from a resource bundle.
In general, an expression can contain fields, variables and parameters, so you can print in a textfield the value of a field and set
the format of the value to present. For this purpose, a textfield expression does not have to return necessarily a string (that’s a
text value): the textfield expression class name property specifies what type of value will be returned by the
expression. It can be one of the following:
An incorrect expression class is frequently the cause of compilation errors. If you use Groovy or JavaScript you can choose
String as expression type without causing an error when the report is compiled. The side effect is that without specifying the
right expression class, the pattern (if set) is not applied to the value.
Figure 5-22 Text tool bar
Figure 5-23 A static text element
Valid Expression Types
java.lang.Object java.sql.Time java.lang.Long
java.lang.Boolean java.lang.Double java.lang.Short
java.lang.Byte java.lang.Float java.math.BigDecimal
java.util.Date java.lang.Integer java.lang.String
java.sql.Timestamp java.io.InputStream
88
iReport Ultimate Guide
Let’s see what properties can be set for a textfield:
The following tables provide some parameters and examples of data and number patterns.
Blank when null If set to true, this option will avoid to print the textfield content if the expression result is a
null object that would be produce the text “null” when converted in a string.
Evaluation time Determines in which phase of the report creation the Textfield Expression has to be
elaborated (an in depth explanation of the evaluation time is available in the next chapter).
Evaluation group The group to which the evaluation time is referred if it is set to Group.
Stretch with
overflow
When it is selected, this option allows the textfield to adapt vertically to the content, if the
element is not sufficient to contain all the text lines.
Pattern The pattern property allows you to set a mask to format a value. It is used only when the
expression class is congruent with the pattern to apply, meaning you need a numeric value
to apply a mask to format a number, or a date to use a date pattern.
Table 5-6 Mask Codes for Dates
Mask Code Date Components Examples
G Era designator AD
y Year 1996; 96
M Month in year July; Jul; 07
w Week in year 27
W Week in month 2
D Day in year 189
d Day in month 10
F Day of week in month 2
E Day in week Tuesday; Tue
a Am/pm marker PM
H Hour in day (0-23) 0
k Hour in day (1-24) 24
K Hour in am/pm (0-11) 0
h Hour in am/pm (1-12) 12
m Minute in hour 30
s Second in minute 55
S Millisecond 978
z Time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone -0800
Report Elements
89
Here there are some examples of date and time formats:
The next table has examples of how certain special characters are parsed as symbols in numeric strings:
Here are some examples of formatting of numbers:
Table 5-7 Examples of Date and Time Formats
Date and Time Patterns Result
"yyyy.MM.dd G 'at' HH:mm:ss z" 2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy" Wed, Jul 4, '01
"h:mm a" 12:08 PM
"hh 'o''clock' a, zzzz" 12 o'clock PM, Pacific Daylight Time
"K:mm a, z" 0:08 PM, PDT
"yyyyy.MMMMM.dd GGG hh:mm aaa" 02001.July.04 AD 12:08 PM
"EEE, d MMM yyyy HH:mm:ss Z" Wed, 4 Jul 2001 12:08:56 -0700
"yyMMddHHmmssZ" 010704120856-0700
Table 5-8 Special Symbols Used in Numeric Strings
Symbol Location Localized? Meaning
0 Number Yes Digit
# Number Yes Digit, zero shows as absent
. Number Yes Decimal separator or monetary decimal separator
- Number Yes Minus sign
, Number Yes Grouping separator
E Number Yes Separates mantissa and exponent in scientific notation.
Need not be quoted in prefix or suffix.
; Subpattern
boundary
Yes Separates positive and negative subpatterns
% Prefix or suffix Yes Multiply by 100 and show as percentage
\u2030 Prefix or suffix Yes Multiply by 1000 and show as per thousand
¤ (\u00A4) Prefix or suffix No Currency sign, replaced by currency symbol. If doubled,
replaced by international currency symbol. If present in a
pattern, the monetary decimal separator is used instead of
the decimal separator.
' Prefix or suffix No Used to quote special characters in a prefix or suffix; for
example, "'#'#" formats 123 to "#123". To create a single
quote itself, use two in a row: "# o''clock".
Table 5-9 Examples of Number Formats
Number Formats Examples
"#,##0.00" 1.234,56
"#,##0.00;(#,##0.00)" 1.234,56 (-1.234.56)
90
iReport Ultimate Guide
To provide a convenient way to define string patterns, iReport provides a simple pattern editor. To open it, click the button
labeled “...” for the pattern property in the property sheet.
5.4 Other Elements
5.4.1 Subreports
The Subreport element is used to include inside a report another report represented by an external Jasper file and feed using the
same database connection used by the parent report or thought a data source that is specified in the subreport properties.
Figure 5-24 Date pattern
Figure 5-25 Subreport element
Report Elements
91
The following briefly describes the characteristics of subreports:
5.4.2 Frame
A frame is an element that can contain other elements and optionally draw a border around them, as shown in Figure 5-26.
Subreport Expression This identifies the expression that will return a subreport expression class object at
run time. According to the return type, the expression is evaluated in order to
recover a Jasper object to be used to produce the subreport. In case the expression
class is set to java.lang.String, JasperReports will look for a file following
the same approach explained for the Image Expression of the Image element.
Subreport Expression
Class
This is the class type of the expression; there are several options, each of one
subtends to a different way to load the JasperReport object used to fill the
subreport.
Using cache This specifies whether to keep in memory the report object used to create the
subreport in order to avoid to reload it all the times it will be used inside the report.
It is common that a subreport element placed, for instance, into the Detail band is
printed more than once (or once for each record in the main dataset). The cache
works only if the subreport expression is of type String since that string is used
as key for the cache.
Connection/Datasource
Expression
This identifies the expression that will return at run time a JDBC connection or a
JRDataSource used to fill in the subreport. Alternatively the user can choose to
avoid to pass any data. This last option is possible and many times it is very useful,
but requires some expedient in order to make the subreport to work. Since a
subreport (like a common report) will return an empty document if no data are
provided, the subreport document should have the document property When No
Data Type set to something like All Sections, No Detail.
Parameters Map
Expression
This optional expression can be used to produce at run time an object of type
java.util.Map. The map must be contain a set of coupled names/objects that
will be passed to the subreport in order to set a value for its parameters. Nothing
disallows to use this expression in order to pass as parameters map to the subreport
a map previously passed as parameter to the parent report.
Subreport parameters This table allows you to define some coupled names/expressions that are useful for
dynamically set a value for the subreport parameters by using calculated
expressions.
Subreport return values This table allows you to define how to store in local variables values calculated or
processed in the subreport (such as totals and record count).
Figure 5-26 Frame element
92
iReport Ultimate Guide
Since a frame is a container of other elements, in the document outline view the frame is represented as a node containing
other elements (Figure 5-27).
A frame can contain other frames, and so on recursively. To add an element to a frame, just drag the new element from the
palette inside the frame. Alternatively you can use the outline view and drag elements from a band into the frame and so on.
The position of an element is always relative to the container position. If the container is a band, the element position will be
relative to the top of the band and the left margin. If the container (or element parent) is a frame, the element coordinates will
be relative to the top left corner of the frame. Since an element dragged from a container to another does not change its top/left
properties, when moving an element from a container to another its position is recalculated based on the new container
location.
The advantages of using a frame to draw a border around a set of elements, with respect to using a simple rectangle element,
are:
When you move a frame, all the elements contained in the frame will move in concert.
While using a rectangle to overlap some elements, the elements inside the rectangle will not treated as overlapped (respect
to the frame), so you will not have problems when exporting in HTML (which does not support overlapped elements).
Finally, the frame will automatically stretch accordingly to its content, and the element position type property of its
elements will refer to the frame itself, not to the band, making the design a bit easier to manage.
5.4.3 Chart
For all the details regarding charts, see Chapter 11.
5.4.4 Crosstab
For all the details regarding crosstabs, see Chapter 15.
5.4.5 Page/Column Break
Page and column breaks are used to force the report engine to make a jump to the next page or column. A column break in a
single column report has the same effect as a page break.
In the design view they are represented as a small line. If you try to resize them, the size will be reset to the default, this
because they are used just to set a particular vertical position in the page (or better, in the band) at which iReport forces a page
or column break.
The type of break can be changed in the property sheet.
Figure 5-27 A frame in the outline view
Report Elements
93
5.5 Adding Custom Components and Generic Elements
Besides the built-in elements seen up to now, JasperReports supports two technologies that enable you to plug-in new
JasperReport objects respectively called “custom components” and “generic elements.” Both are supported by iReport.
Without a specific plug-in offered by the custom element provider, there is not much you can do with it; you can just set the
common element properties. Therefore, a custom element developer should provide a plug-in for iReport through which you
can, at least, add the element to a report (maybe adding a palette item) and modify the element properties (implementing what
is required to display the additional properties in the property sheet when the element is selected.
For more information, see the JasperReports Ultimate Guide.
5.6 Anchors
Image, textfield, and chart elements can be used both as anchors into a document and as hypertext links to external sources or
other local anchors. An anchor is a kind of label that identifies a specific position in the document. The hypertext links and
anchors are defined by means of the Hyperlink dialog, shown in Figure 5-28.
This dialog is divided in two parts. In the upper part is a text area through which it is possible to specify the expression that
will be the name of the anchor. This name can be referenced by other links. If you plan to export your report as a PDF
document, you can use the bookmark level to populate the bookmark tree, making the final document navigation much more
easier. To make an anchor available in the bookmark, simply choose a bookmark level greater than 1. The use of a greater
level makes possible the creation of nested bookmarks.
The lower part is dedicated to the link definition towards an external source or a position in the document. Through the
Hyperlink target option, it is possible to specify whether the exploration of a particular link has to be made in the current
window (this is the pre-defined setting and the target is Self) or in a new window (the target is Blank). This kind of behavior
control makes sense only in certain output formats such as HTML and PDF, specially the last two possible targets (Top and
Parent) used to indicate respectively to display the linked document in the current window but outside eventual frames, and in
the parent window (if available).
The following text outlines some of the remaining options in the Hyperlink window.
Figure 5-28 Hyperlink windows
94
iReport Ultimate Guide
5.6.1 Hyperlink Type
JasperReports provides five types of built-in hypertext links: Reference, LocalAnchor, LocalPage, RemoteAnchor and
RemotePage. Anyway, other types can be implemented and plugged into JasperReports (like the type ReportExecution
used by JasperServer to implement the drill down features). Here is a list of the link types:
5.6.2 Hyperlink Parameters
Sometimes you will need to define some parameters that must be “attached” to the link. The Link parameters table provides a
convenient way to define them. The parameter value can be set using an expression. The parameter expression is supposed to
be a string (since it will be encoded in the URL). But when using custom link types it makes sense to set different types for
parameters.
5.6.3 Hyperlink Tooltip
The tooltip expression is used to set a text to display as tooltip when the mouse is over the element that represents the
hyperlink (this only works when the document is exported in a format that supports this type of interactive use).
Reference The Reference link indicates an external source that is identified by a normal URL.
This is ideal to point, for example, to a servility to manage a record drill-down tools.
The only expression required is the hyperlink reference expression.
LocalAnchor To point to a local anchor means to create a link between two locations into the
same document. It can be used, for example, to link the titles of a summary to the
chapters to which they refer.
To define the local anchor, it is necessary to specify a hyperlink anchor expression,
which will have to produce a valid anchor name.
LocalPage If instead of pointing to an anchor you want to point to a specific current report
page, you need to create a LocalPage link. In this case, it is necessary to specify
the page number you are pointing to by means of a hyperlink page expression (the
expression has to return an Integer object).
RemoteAnchor If you want to point to a particular anchor that resides in an external document, you
use the RemoteAnchor link. In this case, the URL of the external file pointed to will
have to be specified in the Hyperlink Reference Expression field, and the name of
the anchor will have to be specified in the Hyperlink Anchor Expression field.
RemotePage This link allows you to point to a particular page of an external document. Similarly,
in this case the URL of the external file pointed to will have to be specified in the
Hyperlink Reference Expression field, and the page number will have to be
specified by means of the hyperlink page expression.
Some export formats have no support for hypertext links.
Fields, Parameters, and Variables
95
CHAPTER 6FIELDS, PARAMETERS, AND VARIABLES
In a report, there are three groups of objects that can store values:
Fields
Parameters
Variables
iReport uses these objects in data source queries. In order to use these objects in a report, they must be declared with a discrete
type that corresponds to a Java class, such as String or Double. After they have been declared in a report design, the objects
can be modified or updated during the report generation process.
After they have been declared, they can be managed using the Report Inspector view. In the Report Inspector you can modify
or remove objects and declare new objects, as well.
This chapter has the following sections:
Working with Fields
Working with Parameters
Working with Variables
Evaluating Elements During Report Generation
Figure 6-1 Report objects in outline view
96
iReport Ultimate Guide
6.1 Working with Fields
A print is commonly created starting from a data source that provides a set of records composed of a series of fields. This
behavior is exactly like obtaining the results of an SQL query.
iReport displays available fields as children of the Fields node in the document outline view. To create a field, right-click the
Fields node and select the Add Field menu item. The new field will be included as an undefined child node in the Report
Inspector, from which you can configure the field properties by selecting it and using the property sheet (Figure 6-2).
A field is identified by a unique name, a type, and an optional description. Additionally, you can define a set of name/value
pair properties for each field. These custom properties are not used directly by JasperReports, but they can be used by external
applications or by some custom modules of JasperReports (such as a special query executor). You can set the custom
properties with the Properties Editor (Figure 6-2), which you can open by clicking on the Editor button “...” in the column to
the right in the outline view.
Before the introduction of custom properties, iReport included additional information regarding the selected field in its
description field. An example of this would be the definition of fields to be used with an XML data source (that is, a data
source based on an XML file), where the field name can be arbitrary while the description holds an Xpath expression to locate
the value within the XML document.
iReport determines the value for a field based on the data source you are using. For instance, when using an SQL query to fill
a report, iReport assumes that the name of the field is the same as the name of a field in the query result set. You must ensure
that the field name and type match the field name and type in the data source. We will see, though, how you can systematically
declare and configure large numbers of fields using the tools provided by iReport. Since the number of fields in a report can be
quite large (possibly reaching the hundreds), iReport provides different tools for handling declaration fields retrieved from
particular types of data sources.
Figure 6-2 Field Properties dialog
Figure 6-3 Field - Custom Properties
Fields, Parameters, and Variables
97
Inside each report expression (like the one used to set the content of a textfield) iReport specifies a field object, using the
following syntax:
$F{<field name>}
where <field name> must be replaced with the name of the field. When using a field expression (for example, calling a
method on it), keep in mind that it can have a value of null, so you should check for that condition. An example of a Java
expression that checks for a null value is:
($F{myField} != null) ? $F{myFiled}.doSomething() : null
This method is generally valid for all the objects, not just fields. Using Groovy or JavaScript this is rarely a problem, since
those languages handle a null value exception in a more transparent way, usually returning an empty string. This is another
reason why I recommend that you use Groovy or JavaScript instead of Java.
In Chapter 10 we’ll see that in some cases a field can be a complex object, like a JavaBean, not just a simple value like a
String or an Integer. A trick to convert a generic object to a String is to concatenate it to a empty string this way:
$F{myfield}+ “”
All Java objects can be converted to a string; the result of this expression depends on the individual object implementation
(specifically, by the implementation of the toString() method). If the object is null, the result will return the literal text
string “null” as a value.
6.1.1 Registration of the Fields from a SQL Query
The most common way to fill a report is by using an SQL query. iReport provides several tools to work with SQL, including a
query designer, and a way to automatically retrieve and register the fields derived from a query in the report.
You can open the query dialog by clicking the cylinder icon in the designer tool bar (Figure 6-4).
Before you open the query dialog, however, pay attention to the active connection/data source (the selected item in the combo
box located in the main tool bar). All the operations performed by the tools in the query dialog will use that data source, so
make sure that you select the correct connection/data source in the combo box.
The report query dialog includes four query tools, each accessed by the appropriate tab, as shown in Figure 6-5:
Report query
JavaBean Datasource
DataSource Provider
CSV Datasource
Right now I’m going to describe for you the features of the Report query tab. Here you can define a query that iReport will
use when generating a report.
Figure 6-4 Query dialog button
98
iReport Ultimate Guide
iReport does not need you to define a query in order to generate a report. In fact, iReport could obtain data records from a data
source that is not defined by a query execution. Regardless, here is where you define it. The language of the query can be one
of those items listed in the combo box on the top of the query dialog. JasperReports supports the most common query
languages:
SQL
HQL
EJBQL
Xpath
MDX (both the standard and XMLA-encapsulated versions)
Let’s focus on SQL. If the selected data source is a JDBC connection, iReport will test the access connection to the data source
as you define the query. This allows iReport to identify the fields using the query metadata in the result set. The design tool
lists the discovered fields in the bottom portion of the window. For each field, iReport determines the name and the Java type
specified for that field by the JDBC driver.
A query that accesses one or more tables containing a large amount of data may require a long delay while iReport scans the
data source to discover field names. You may want to disable the Automatically Retrieve Fields option in order to quickly
finish your query definition. When you have completed the query, click the Read Fields button in order to start the fields
discovery scan.
In case of an error during the query execution (due to a syntax error or to an unavailable database connection), an error
message will be displayed instead of the fields list.
The field name scan may return a large number of field names if you are working with complex tables. I suggest that you
review the list of discovered names and remove any fields that you are not planning to use in your report, in order to reduce
unnecessary complexity.When you click the OK button all the fields in the list will be included in the report design. You can
also remove them later in the outline view, but it’s a good idea at this point in the design process to remove any field names
that you won’t be using.
Figure 6-5 Query dialog
All fields used in a query must have a unique name. Use alias field names in the query for fields having the same
name.
Fields, Parameters, and Variables
99
6.1.2 Accessing the SQL Query Designer
iReport provides a simple visual query designer to help you create simple SQL queries without having to know a particular
language. You can access the tool by clicking the button labeled Query designer (a JDBC connection must be active, and the
selected language of the query must be SQL).
This SQL query designer, which comes from the SQLeonardo open source project, provides a drag-and-drop way to create
queries (see Figure 6-6).
To create a query you need to drag the required tables into the main panel. Check which fields you will need. The designer
allows you to define table joins. To join two tables, drag the field of one table over the field of another. Edit the join type by
right-clicking the red, square joint icon in the middle of the join line. To add a condition, right-click the Where node in the
query tree. To add a field to the Group By and Order By nodes, right-click a field under the SELECT node.
6.1.3 Registration of the Fields of a JavaBean
One of the most advanced features of JasperReports is the ability to manage data sources that are not based on simple SQL
queries. One example of this is JavaBean collections. In a JavaBean collection, each item in the collection represents a record.
JasperReports assumes that all objects in the collection are instances of the same Java class. In this case the “fields” are the
object attributes (or even attributes of attributes).
By selecting the JavaBean Datasource tab in the query designer, you can register the fields which correspond to the specified
Java classes. The concept here is that you will know which Java classes correspond to the objects that you will be using in your
report.
Figure 6-6 SQLeonardo Query Designer
100
iReport Ultimate Guide
Suppose that you are using objects of this Java class:
com.jaspersoft.ireport.examples.beans.PersonBean
To register fields for the class:
1. Put the class name in the name field and click Read attributes. iReport will scan the class.
2. Check the scan results to make sure that iReport has captured the correct object attributes for the class type.
3. Select the fields you want to use in your report and click Add selected field(s).
4. iReport creates new fields corresponding to the selected attributes and adhesion to the list. The description, in this case,
will be used to store the method that the data source must invoke in order to retrieve the value for the specified field.
iReport parses a description such as address.state (with a period character between the two attributes) as an attribute path.
This attribute path will be passed to the function getAddress() in order to locate the target attribute, and then to
getState() in order to query the status of the attribute. Paths may be arbitrary long, and iReport can recursively parse
attribute trees within complex JavaBeans and in order to register very specific fields.
We have just discussed the two tools used most frequently to register fields, but we’re not done yet. There are many other tools
you can use to discover and register fields, for instance, the HQL and XML node mapping tools. These will be discussed in
Chapter 10.
6.1.4 Fields and Textfields
To print a field in a text element, you will need to set the expression and the textfield class type correctly. You may also
need to define a formatting pattern for the field. For more details about format patterns see 5.3.2, “Textfields,” on page 87.
To create a corresponding textfield, drag the field you wish to display from the Report Inspector view into the design panel.
iReport will create a new textfield with the correct expression (e.g., $F{fieldname}) and assign the correct class name.
Figure 6-7 JavaBeans data source fields registration
Fields, Parameters, and Variables
101
6.2 Working with Parameters
Parameters are values usually passed to the report from the application that originally requested it. They can be used for
configuring features of a particular report during report generation (such as the value to use for a condition in a SQL query)
and to supply additional data to the report that cannot properly provided by the data source (e.g., a custom title for the report,
an application-specific path to search for images, or even a more complex object like an image).
Just as with other report objects, parameters must have a class type and must be declared in the report design (see Figure 6-8).
The type of the parameters may be arbitrary, but the parameter name must be unique.
The property Use as prompt is not used directly by JasperReports. It is a special flag for the parameter that may be used by
external applications; you can examine the report template to discover what parameters you should use to prompt for input.
The Default Value Expression permits you to set a pre-defined value for the parameter. This value will be used if no
value is provided for the parameter from the application that executes the report. The type of value must match the type
declared in Parameter Class. In this expression it is not possible to use fields and/or variables, since the value of the
parameter must be set before fetching the first record from the data source.
You may legally define another parameter as the value of Default Value Expression, but this method requires careful
report design. iReport parses parameters in the same order in which they are declared, so a default value parameter must be
declared before the current parameter. I realize this sounds a bit tricky, but it can be useful to employ a parameter that depends
on another one, especially if we want to process it.
In the next section we will see how to use a parameter in an SQL query to specify not just the value of a parameter, but a piece
of or even the whole SQL query. This will allow you to dynamically create an input-dependent query to be stored in a
parameter.
The parameter Description is another attribute that is not used directly by JasperReports, but like the Use as a prompt
attribute, may be passed to an external application.
Finally, just as with fields, you may specify pairs of type name/value as properties for each parameter. This is just a way to add
extra information to the parameter, information that will be used by external applications. For example, the designer can use
properties to include the description of the parameter in different languages, or perhaps add instructions about the format of the
input prompt.
6.2.1 Using Parameters in a Query
Generally, parameters can be used in the query associated with a report even if not all the languages support them. In this
chapter we will focus on using parameters in SQL queries, which is probably the most common type of query.
Suppose we have a report that displays information about a customer. When we generate the report we would need to specify
the ID of the customer to display. In order to get data regarding the customer we need to pass this information to the query; in
other words, we want to filter the query to obtain only the data relevant to a particular customer ID. The query will look like
this:
select * from customers where CUSTOMERID = $P{MyCustomerId}
Figure 6-8 Parameter Definition
102
iReport Ultimate Guide
MyCustomerID is a parameter, and the syntax to use for the parameter in the query is the same one used when referring to a
parameter in an expression. Without going into too much depth on how parameters work in SQL, let’s just say that
JasperReports will interpret this query as:
select * from customers where CUSTOMERID = ?
The question mark character is the canonical symbol in SQL that says “here goes a value provided to the SQL statement before
query execution.” This is exactly what JasperReports will do: it will execute the query, passing the value of each parameter
used in the query to the SQL statement.
This approach has a major advantage with respect to concatenating the parameter value to the query string—you do not have
to take care of special characters or sanitize your parameter, since the database will do it for you. At the same time, this method
places limits on the control you have on the query structure. For example, you cannot specify a portion of a query with a
parameter (for example, storing the entire WHERE or GROUP BY clause). The solution is to use this special syntax:
$P!{<parameter name>}
Note the exclamation mark after the $P. The exclamation mark notifies JasperReports not to bind the parameter to an SQL
parameter (using the question mark (?) like in the previous case), but rather to calculate the value of the parameter and
evaluate it as a raw subsection of a query. For example, if you have a parameter named MyWhere with the value of "where
CUSTOMERID = 5", the query:
select * from customers $P!{CUSTOMERID}
will be transformed into:
select * from customers where CUSTOMERID = 5
without using the logic of the SQL parameter. The drawback is that you must be 100percent sure that the parameter value is
correct in order to avoid an error during the query execution.
6.2.2 IN and NOTIN clause
JasperReports provides a special syntax to use with a where condition: the clause IN and NOTIN.
The clause is used to check whether a particular value is present in a discrete set of values. Here is an example:
SELECT * FROM ORDERS WHERE SHIPCOUNTRY IS IN ('USA','Italy','Germany')
The set here is defined by the countries USA, Italy and Germany. Assuming we are passing the set of countries in a list (or
better a java.util.Collection) or in an array, the syntax to make the previous query dynamic in reference to the set of
countries is:
SELECT * FROM ORDERS WHERE $X{IN, SHIPCOUNTRY, myCountries}
where myCountries is the name of the parameter that contains the set of country names. The $X{} clause recognizes three
parameters:
Type of function to apply (IN or NOTIN)
Field name to be evaluated
Parameter name
JasperReports will handle special characters in each value. If the parameter is null or contains an empty list, meaning no
value has been set for the parameter, the entire $X{} clause is evaluated as the always true statement “0 = 0”.
Fields, Parameters, and Variables
103
6.2.3 Built-in Parameters
JasperReports provides some built-in parameters (they are internal to the reporting engine) that you may read but cannot
modify. These parameters are presented in the following table:
Table 6-1 JasperReports Built-in parameters
Parameter Explanation
REPORT_PARAMETERS_MAP This is the java.util.Map passed to the fillReport method; it
contains the parameter values defined by the user.
REPORT_CONNECTION This is the JDBC connection passed to the report when the report is
created through a SQL query.
REPORT_DATASOURCE This is the data source used by the report when it is not using a JDBC
connection.
REPORT_SCRIPTLET This represents the scriptlet instance used during creation. If no scriptlet
is specified, this parameter uses an instance of
net.sf.jasperreports.engine.JRDefaultScriptlet.*
* Starting with JasperReports 1.0.0, an implicit cast to the provided scriptlet class is performed. This simplifies many
expressions that use the provided scriptlet class.
IS_IGNORE_PAGINATION You can switch the pagination system on and off with this parameter (it
must be a Boolean object). By default, pagination is used except when
exporting to HTML and Excel formats.
REPORT_LOCALE This is used to set the locale used to fill the report. If no locale is
provided, the system default will be used.
REPORT_TIME_ZONE This is used to set the time zone used to fill the report. If no value is
provided, the system default will be used.
REPORT_MAX_COUNT This is used to limit the number of records filling a report. If no value is
provided, no limit will be set.
REPORT_RESOURCE_BOUNDLE This is the resource bundle loaded for this report. See Chapter 10 for
how to provide a resource bundle for a report.
REPORT_VIRTUALIZER This defines the class for the report filler that implements the
JRVirtualizer interface for filling the report.
REPORT_FORMAT_FACTORY This is an instance of a
net.sf.jasperreports.engine.util.FormatFactory. The
user can replace the default one and specify a custom version using a
parameter. Another way to use a particular format factory is by setting
the report property format factory class.
REPORT_CLASS_LOADER This parameter can be used to set the class loader to use when filling
the report.
REPORT_URL_HANDLER_FACTORY Class used to create URL handlers. If specified, it will replace the
default one.
REPORT_FILE_RESOLVER This is an instance of
net.sf.jasperreports.engine.util.FileResolver used to
resolve resource locations that can be passed to the report in order to
replace the default implementation.
REPORT_TEMPLATES This is an optional collection of styles (JRTemplate) that can be used
in the report in addition to the ones defined in the report.
104
iReport Ultimate Guide
6.2.4 Relative Dates
iReport 5.0 introduces relative dates. This feature enables you create reports that to filter information based on a date range
relative to the current system date. To do this, use the following template:
<Keyword> <+/-> <N> where:
<Keyword> indicates the time span you want to use. Options include: DAY, WEEK, MONTH, QUARTER, SEMI, and YEAR.
<+/-> indicates whether the time span occurs before or after the chosen date.
<N> indicates the number of the above-mentioned time spans you want to include in the filter.
For example, if you want to look at Sales for the prior month, your expression would be MONTH - 1.
The class attribute of a JR Parameter of type Relative Date should have one of the following values:
net.sf.jasperreports.engine.rd.DateRange – if you want to use java.util.Date (Date only).
For example: <parameter name=”myParameter” class="net.sf.jasperreports.engine.rd.DateRange”>
net.sf.jasperreports.engine.rd.TimestampRange – if you want to use java.sql.Timestamp (Date and
Time).
For example: <parameter name=”myParam” class="net.sf.jasperreports.engine.rd.TimestampRange”>
Following are two examples of when and how to use relative dates:
If you want to set a relative date as a default value expression of a JR parameter, use the following relative date-builder
pattern:
new DateRangeBuilder("DAY-1").toDateRange()
new DateRangeBuilder("WEEK").set(Timestamp.class).toDateRange()
new DateRangeBuilder("2012-08-01").toDateRange()
new DateRangeBuilder("2012-08-01 12:34:56").toDateRange();
For queries, Relative dates are not supported by the $P{} function because it can handle only a limited number of classes
(standard Java classes Integer, String etc.). Instead, a new implementation of pluggable functions and parameters in
JasperReports supports relative dates with $X{} functions.
Relative dates are sensitive to time zones. The relative date expression is calculated in the time zone of the logged-in
user.
Only one property is configurable: the start day of the week does not depend on locale.
Problem Solution
Find all purchases made
previous to this quarter
Relative data parameter called STARTDATE takes this value: QUARTER
"QUARTER" evaluates to the first day (the first instant, really) of this quarter.
SQL: select * from orders where order_date < $P{STARTDATE}
Find all purchases made in this
quarter
Valid answer:
select * from orders where order_date >= QUARTER and
order_date < QUARTER + 1
Better answer using DateRanges:
select * from orders where $X{EQUAL, order_date, QUARTER}
Fields, Parameters, and Variables
105
The following is a JRXML example that shows data from the previous day:
<parameter name=“myParameter” class=“net.sf.jasperreports.engine.rd.DateRange”>
<defaultValueExpression>
<![CDATA[
new DateRangeBuilder("DAY-1").toDateRange()
]]>
</defaultValueExpression>
</parameter>
<queryString>
<![CDATA[
Select * from account where $X{EQUAL, OpportunityCloseDate, SelectedDateRange}
]]>
</queryString>
Older reports which have date parameters will work just as before, and Relative Dates functionality will be
unavailable. In order to make older reports support relative dates, you will need to modify the JRXML: change the
parameter class, and, if needed, set a default value expression. In addition, remember to use the $X{} function
instead of $P{}.
106
iReport Ultimate Guide
Relative dates currently do not support keywords like “Week-To-Date”(from the start of the current week to the end of the
current day). However, you can emulate that by using IS_BETWEEN:
In JRXML, the query use is:$X{IS_BETWEEN, column, startParam, endParam}
where startParam has value WEEK and endParam has value DAY.
Likewise, you can do the same for other time ranges: Year-To-Week, Year-To-Month, etc.
6.2.5 Passing Parameters from a Program
iReport passes parameters from a program “caller” to the print generator using a class that extends the java.util.Map
interface. Consider the code in Code Example 3-2 on page 43, in particular the following lines:
fillReport is a key method that allows you to create a report instance by specifying the file name as a parameter, a
parameter map, and a data source. (This example uses a dummy data source created with the class JREmptyDataSource and
an empty parameter map created using a java.util.HashMap object.)
Let’s see how to pass a simple parameter to a reporting order to specify the title of a report.
The first step is to create a parameter in the report to host the title (that will be a String). We can name this parameter
REPORT_TITLE and the class will be java.lang.String (see Figure 6-9).
...
HashMap hm = new HashMap();
...
JasperPrint print = JasperFillManager.fillReport(
fileName,
hm,
new JREmptyDataSource());
...
Figure 6-9 Definition of the parameter to host the title
Fields, Parameters, and Variables
107
All the other properties can be left as they are; in particular, we don’t want to set a default value expression. By dragging the
parameter into the Title band we can create a textfield to display the REPORT_TITLE parameter (shown in Figure 6-10).
This example report is very simple. We just want to focus our attention on how to display the parameter.
To set the value of the REPORT_TITLE parameter in our application, modify the code of the previous source code example by
adding:
We have included a value for the REPORT_TITLE parameter in the parameter map. You do not need to pass a value for all the
parameters. If you don’t provide a value for a certain parameter, JasperReports will assign the value of Default Value
Expression to the parameter with the empty expression evaluated as null.
Printing the report, iReport includes the String This is the title of the report in the Title band. In this case we just
used a simple String. However, it is possible to pass much more complex objects as parameters, such as an image
(java.awt.Image) or a data source instance configured to provide a specified subreport with data. The most important thing
to remember is that the object passed in the map as the value for a certain parameter must have the same type (or at least be a
super class) of the type of the parameter in the report. Otherwise, iReport fails to generate the report, returning a
ClassCastException error. This is actually pretty obvious; you cannot, for example, assign the value of a
java.util.Date to a a parameter declared as an Integer.
Figure 6-10 Design panel with the REPORT_PARAMETER displayed in the title band
...
HashMap hm = new HashMap();
hm.put(“REPORT_TITLE”,”This is the title of the report”);
...
JasperPrint print = JasperFillManager.fillReport(
fileName,
hm,
new JREmptyDataSource());
...
108
iReport Ultimate Guide
6.3 Working with Variables
Variables are objects used to store the results of calculations, such as subtotals, sums, and so on. Again, just as with fields and
parameters, you must define the Java type of a variable when it is declared.
To add a new variable, select the variables node in the outline view and select the menu item Add Variable.
Figure 6-11 shows the property sheet for a variable. Below is a list describing the meaning of each property.
Figure 6-11 Variable Properties dialog
Name This is the name of the variable. The name must be unique (meaning you cannot have
two variables with the same name). Similar to fields and parameters, you refer to a
variable using the following syntax in an expression:
$V{<variable name>}
Variable Class This is the Java type of the variable. In the combo box, you can see some of the most
common types such as java.lang.String and java.lang.Double.
Calculation This is the type of a pre-defined calculation used to store the result by the variable.
When the pre-defined value is Nothing, it means “don’t perform any calculation
automatically.” JasperReports performs the specified calculation by changing the
variable’s value for every new record that is read from the data source.
To perform a calculation of a variable means to evaluate its expression (defined in the
Variable Expression property). If the calculation type is Nothing, JasperReports will
assign to the variable the value that resulted from the evaluation of the variable
expressions. If a calculation type is other than Nothing, the expression result will
represent a new input value for the chosen calculation, and the variable value will be the
result of this calculation. The calculation types are listed in Table 6-2.
Table 6-2 Calculation types for the variables
Type Definition
Distinct Count This counts the number of different expression results; the order of expression
evaluation does not matter.
Sum This adds to each iteration the expression value to the variable’s current value.
Average This calculates the arithmetic average of all the expressions received in input. From a
developer’s point of view, declaring a variable to type System is pretty much like just
declare a variable in a program, without actually use it. Someone will set a value for it.
This “someone” is usually a scriptlet tied to the report or some other Java code executed
through an expression.
Lowest This returns the lowest expression value received in input.
Fields, Parameters, and Variables
109
Highest This returns the highest expression value received in input.
StandardDeviation This returns the standard deviation of all the expressions received in input.
Variance This returns the variance of all the expressions received in input.
System*This does not make any calculation, and the expression is not evaluated. In this case,
the report engine keeps only the last value set for this variable in memory.
Reset type This specifies when a variable value has to be reset to the initial value (or to null if no
initial value expression has been provided). The variable reset concept is fundamental
when you want to make group calculations, such as subtotals or averages. When a
group changes, you should reset the variable value and restart the calculation. The
reset types are listed in Table 6-3.
* From a developer’s point of view, declaring a variable to type System is pretty much like just declaring a variable in a
program, without actually using it. Someone will set a value for it. This “someone” is usually a scriptlet tied to the report or
some other Java code executed through an expression.
Table 6-3 Reset types
Reset Type Description
None The initial value expression is ignored.
Report The variable is initialized only once at the beginning of report creation by using the initial
value expression.
Page The variable is initialized again in each new page.
Column The variable is initialized again in each new column (or in each page if the report is
composed of only one column).
Group The variable is initialized again in each new group (the group specified in the Reset
group setting)
Reset Group This specifies the group that determines which variable to reset when the Group reset
type is selected.
Increment type This specifies when a variable value has to be evaluated. By default, a variable is
updated every time a record is fetched from the data source, but sometimes the
calculation we want to perform must be performed only at certain times. The increment
types are the same as the calculation types listed in Table 6-2.
To clarify the use of increment type a little bit, consider this example: to have a report
with a list of names ordered alphabetically and grouped by the first letter, we have the
group for the letter A containing a certain amount of names, the group B, and so on to Z.
Suppose we want to calculate with a variable the average number of names for each
letter. We need to create a variable that performs an average calculation on the number
or records present in each group. To correctly perform this calculation, the variable must
be updated only when the first letter in the names changes, which happens at the end of
each group. In this case, the increment type (meaning the exact moment at which a new
input value must be acquired to perform the calculation) should be Group.
Increment group This specifies the group that determines the variable increment if the Group increment
type is selected.
Custom
Incrementer
Factory Class
This is the name of a Java class that implements the JRIncrementerFactory
interface, which is useful for defining operations such as the sum of non-numerical
types. In other words, a developer has the ability to implement his custom calculation.
Table 6-2 Calculation types for the variables, continued
Type Definition
110
iReport Ultimate Guide
As with parameters, JasperReports provides some built-in variables (which are directly managed by the reporting engine). You
can read these variables but cannot modify them. Table 6-4 lists the built-in variables.
6.4 Evaluating Elements During Report Generation
There is a strict correlation between the physical location of an element in a report and the point at which JasperReports
evaluates the element during report generation. When the report filling process starts, JasperReports retrieves the first record
from the data source, updates the value of the record’s fields, and recalculates the necessary variables. The first band to be
evaluated is the title, followed by the page header, the column header, group headers, detail, and so on. When all the detail
bands have been filled, the engine next retrieves the second record, updating all the fields and variables again, and continues
the fill process. By default, the engine evaluates the expression of textfield and image elements as they are encountered during
the report generation process.
Sometimes this is not what the we want. An example is when we want to show the final result of a calculation in a textfield that
is evaluated before the end of the calculation, such as when printing the total number of pages in the page footer (as in the
example shown in Figure 6-12). There is no variable that contains the total number of pages in the report, there is just the
Variable
expression
This is the expression that identifies the input value of the variable to each iteration. The
result must be congruent to the type of the variable and its calculation. For example, if
we are just counting objects, the expression can return any kind of result, and the
variable will be incremented only when a not-null result is provided, independently of
the expression result type.However, if we are summing something, the calculator
expects an object of the same type as the variable (like a Double or an Integer).
Initial value
expression
This is an expression used to set the initial value for the variable. If blank, the variable is
initialized to null.
Table 6-4 Built-in variables
Variable Name Definition
PAGE_NUMBER Contains the current number of pages. At “report” time, this variable will contain the total
number of pages.
COLUMN_NUMBER Contains the current number of columns.
REPORT_COUNT Contains the current number of records that have been processed.
PAGE_COUNT Contains the current number of records that have been processed in the current page.
COLUMN_COUNT Contains the current number of records that have been processed during the current
column creation.
<group name>_COUNT Contains the current number of records that have been processed for the group
specified as a variable prefix.
Figure 6-12 How to print Page X of Y using the evaluation time
Table 6-3 Reset types, continued
Reset Type Description
Fields, Parameters, and Variables
111
PAGE_NUMBER variable that defines the value of the current page number. So we have to force JasperReports to wait to fill that
particular element until the calculation process completes.
Using the example of Page X of Y, we need two textfields:
A textfield to print the current page number (or better the string “Page X of”), where X is the current value of the variable
PAGE_NUMBER.
A second textfield to print Y (the total number of pages).
For the second textfield we set the evaluation time to REPORT, which signifies “when the last page has been reached.”At that
time, the value of PAGE_NUMBER will contain the total number of pages.
You can use this method to set the evaluation time for any textfield or image. For example, you can use it to print a subtotal in
the header of a group. The calculation requires the records in the group to be processed first, but it is possible to place a
textfield showing the variable associated with the calculation in a textfield of the group header, with the evaluation time set to
GROUP (and the evaluation group to the proper group).
Two particular evaluation times deserve special attention: BAND and AUTO:
BAND forces JasperReports to evaluate a variable that is the result of a calculation performed after processing the entire
band. This is often used in the Detail band in two cases: a value returned from a subreport (for example, the number of
records printed in the subreport) and a value of a variable that was set by an external agent, such as a scriptlet.
AUTO evaluation time occurs when the last record of the given dataset is processed; the time is defined by the reset type,
which, in these cases, would usually be REPORT or GROUP. It allows you to mix values that are determined at different
times, such as the current value of a field and the calculated value of a variable. The most common use is calculating a
percentage. Suppose we have a list of numbers, and we want to print the percentage of incidence for each single number
with respect to the total of all the numbers. You can calculate the percentage by dividing the current value of evaluation
time NOW by a variable that calculates the total when the report completes.
Here comes the conflict: we need to consider two values having different evaluation times. The AUTO evaluation time
provides the solution. JasperReports will use the evaluation time NOW for the field named in the expression, while waiting
to evaluate the variable until the evaluation time that corresponds to the field’s reset type.
For another use of evaluation times and reset types, see 19.2.2, “Printing Page X of Y in a Single Textfield,” on page 349.
112
iReport Ultimate Guide
Bands and Groups
113
CHAPTER 7BANDS AND GROUPS
In this chapter, I will explain how to manage bands and groups when using iReport. In Chapter 4, you learned how reports are
structured, and you have seen how the report is divided into bands. Here, in this chapter, you will see how to adjust the
properties of the bands. You will also learn how to use groups, how to create breaks in a report, and how to manage subtotals.
This chapter has the following sections:
Modifying Bands
Working with Groups
Other Group Options
7.1 Modifying Bands
JasperReports divides a report into eight main bands and a background (plus the special No Data band). To this set of standard
bands you can add two supplemental bands for each group: the Group Header band and the Group Footer band.
When you select a band in the report outline view, the band properties are displayed in the property sheet (Figure 7-1).
The band height represents the height of the band at design time. If the content of the band expands vertically (that is, due to a
subreport or a long text in a textfield with the Stretch with Overflow property set to true), the band increases in height
accordingly during report execution. The band height is expressed in pixels (always using the same resolution of 72 pixels per
inch). You can set the height with the property sheet or by dragging the bottom border of the band directly into the designer
window.
Figure 7-1 Band properties
114
iReport Ultimate Guide
The Print When Expression property is used to hide or display the band under the circumstances described by the
expression. The expression must return a Boolean value. In particular, it must return true to display the band and false to hide
it. By default, when no value is defined for the expression, the band is displayed.
JasperReports reserves enough space in a page for bands like the title, the page header and footer and the column header and
footer. All the other bands cannot fit in the remaining space when repeated several times. This may result in a Detail band
beginning in one page and ending on another page.
If you want to be ensure that a band displays completely within one page, deselect the Split allowed property. Every time
the band is printed, JasperReports will check the available space in the current page. If it is not enough, the band will start on
the next page. Of course, this does not mean that the band will completely fit in the next page, this still depends of the band
content.
The default report template includes all the pre-defined bands, except the Last Page Footer and the No Data bands. If you are
not interested in using a band, you can remove it by right-clicking the band (or the band node in the outline view) and selecting
the menu item Delete Band. When a band is no longer present in the report, it is displayed as a grayed node (see Figure 7-2).
To add the band to the report, right-click the band and select Add Band.
In general, there is no valid reason to remove a band apart the generation of a less complex JRXML file (the report source
code). In order to prevent the printing of a band, set its height to 0. The only exceptions are the Last Page Footer and No Data
bands.
If present, the Last Page Footer band always replaces the Page Footer band in the last page, so if we don’t want or need this
behavior the band must be not present. The No Data band is a very special band that replaces the entire report if the data source
does not contain any records and if, at the document level, the property When No Data Type has been set to No Data
Section.
7.2 Working with Groups
Groups allow you to organize the records of a report in order to create some structures. A group is defined through an
expression. JasperReports evaluates this expression thus: a new group begins when the expression value changes. An
Consecutive zero-height bands may become obscured while working in the design panel. You can increase the height
of a selected band by pressing the Shift key while dragging the bottom margin of the band down.
Figure 7-2 Adding a pre-defined band
Bands and Groups
115
expression may be represented just by a specific field (that is, you may want to group a set of contacts by city, or country), but
it can be more complex as well. For example, you may want to group a set of contact names by initial letter.
Each group can have one or more header and one or more footer bands. Group headers and footers are printed just before and
after the Detail band. You can define an arbitrary number of groups (that is, you can have a first-level group that contains
contacts by Country and a nested group containing the contacts in each country by City).
The order of the groups in the Report Inspector determines the groups’ nesting order. The group order can be changed by right-
clicking a group node (header or footer) and selecting the Move Group Up or Move Group Down menu items (see Figure 7-4
on page 115).
Figure 7-3 Group bands
Figure 7-4 Changing the groups order
116
iReport Ultimate Guide
JasperReports groups records by evaluating the group expression. Every time the expression’s value changes, a new group
instance is created. The engine does not perform any record sorting if not explicitly requested, so when we define groups we
should always provide for the sorting. For instance, if we want to group a set of addresses by country, we have to sort the
records before running the report. We can use a SQL query with an ORDER BY clause or, when this is not possible (that is,
when obtaining the records from a data source which does not provide a way to sort the records, like an XML document or an
Excel file), we can request that JasperReports sort the data for us. This can be done using the sort options available in the
iReport query window (Figure 7-5).
In order to use the Sort options, you must have some fields already registered in the report. Sorting can only be performed on
fields (you cannot sort records using an expression). You can define a sort using any of the fields in the database. Each field
can use a different sort type (ascending or descending). The sorting is performed in memory, so it’s use is discouraged if you
are working with very large amounts of data, but it is useful with a reasonable number of records (depending on the available
memory).
Let’s see how groups work in an example. Suppose you have a list of people. You want to create a report where the names of
the people are grouped last-name-first as in a phone book. Run iReport and open a new empty report. Next, take the data from
a database by using a SQL query with a proper ORDER BY clause (we will use the sample database provided with
JasperReports). For this example, use the following SQL query:
SELECT * FROM ADDRESS ORDER BY LASTNAME, FIRSTNAME
The selected records will be ordered according to the last then first name of the customers. The fields selected by the query
should be ID, FIRSTNAME, LASTNAME, STREET and CITY.
Figure 7-5 Sorting Options
Bands and Groups
117
Before continuing with creating your group, make sure that everything works correctly by inserting in the Detail band the
FIRSTNAME, STREET and CITY fields (move them from the outline view to the Detail band, as shown in Figure 7-6).
Then create a layout similar to the one proposed in Figure 7-7 and preview the report.
The result should be similar to that of Figure 7-8.
Figure 7-6 Dragging a field into the Detail band
Figure 7-7 Layout before adding the groups
118
iReport Ultimate Guide
What we have is just a simple flat report showing an ordered list of addresses. Let’s proceed to group the records by the first
letter of the last name. The first letter of the name can be extracted with a simple expression (both in Groovy and JavaScript).
Here is:
$F{LASTNAME}.charAt(0)
If you use Groovy or JavaScript as suggested, remember to set it in the document properties
To add the new group to the report, select the document root node in the outline view and select the Add Report Group menu
item (Figure 7-10).
This opens a simple wizard (Figure 7-10). Use it to set the group name (that is, First_Letter) and add the expression that
extracts the first letter from a string.
Figure 7-8 The addresses not grouped
Figure 7-9 Add Report Group
Bands and Groups
119
In the second step (Figure 7-11) we have the option of creating header and footer bands for the group. Select both and click
Finish to complete the group creation.
The new two bands (Group Header and Group Footer) will appear in the design window, and the corresponding nodes will be
added to the report structure in the outline view (Figure 7-12).
Figure 7-10 The first step of the new group wizard
Figure 7-11 The second step of the new group wizard
120
iReport Ultimate Guide
When you add a group to the document, iReport creates an instance of the built-in variable <group name>_COUNT for the
new group. In our case, the variable is named First_Letter_COUNT (Figure 7-13). It represents the number of records
processed for the group; if we display this variable in a textfield in the group footer, it will display how many records the group
contains.
Now we can add some content to the group header and footer. In particular, we can add the initial letter to which the group
refers, and we can add in the footer the First_Letter_COUNT variable. For the letter, just add a Textfield in the group header
and use the same textfield expression as you did for the group. The textfield class can be set to String (because we are using
Groovy or JavaScript). If you use Java, the expression for the textfield should be changed a little bit. Java is a bit more severe
in terms of type matching, and since the charAt() function returns a char, we can convert this value in a String by
concatenating an empty string. (This is actually a dirty but simple way to cast any Java object in a String without checking if
the object is null). So the expression in Java should be:
“” +$F{LASTNAME}.charAt(0)
Figure 7-12 The new group bands in the design panel
Figure 7-13 The group in the outline view
Bands and Groups
121
Figure 7-14 shows the final definition of the report.
The blue field (in the group footer) displays the variable First_Letter_COUNT that we created by dragging this variable
from the outline view into Group Footer band. If we want to display the same value in the group header, we need to change the
textfield evaluation time to Group and set the evaluation group to First_Letter. See Section 6.4, “Evaluating Elements
During Report Generation,” on page 110 for a discussion of evaluation times.
Figure 7-15 shows the final generated report.
Figure 7-14 Final Layout
122
iReport Ultimate Guide
Figure 7-15 The final result
Bands and Groups
123
7.3 Other Group Options
In the previous example, we learned how to create a group using the group wizard, we set the group name, and we set the
group expression. There are many other options that you can set to control how a group is displayed. By selecting a group band
in the outline view (header or footer), in the property sheet you will see all these options (Figure 7-16):
Figure 7-16 Group options
Group Expression This is the expression that JasperReports will evaluate against each record. When
the expression changes in value, a new group is created. If this expression is
empty, it is equal to null, and since a null expression will never change in value,
the result is a single group header and a single group footer, respectively, after the
first column header and before the last column footer.
Start on a New Column If this option is selected, it forces a column break at the end of the group (that is, at
the beginning of a new group); if in the report there is only one column, a column
break becomes a page break.
Start on a New Page If this option is selected, it forces a page break at the end of the group (that is, at
the beginning of a new group).
Reset Page Number This option resets the number of pages at the beginning of a new group.
Reprint header If this option is selected, it prints the Group Header band on all the pages on which
the group’s content is printed (if the content requires more than one page for the
printed report).
Min Height to Start New Page If the value is other than 0, JasperReports will start to print this group on a new
page if the space remaining on the current page is less than the minimum specified.
This option is usually used to avoid splitting a report section composed of fields
that we want to remain together (such as a title followed by the text of a
paragraph).
124
iReport Ultimate Guide
Footer Position This option controls where to place the footer bands. By default they are placed
just after the end of the group (without leaving any space before the previous
band). This behavior can be changed, the available options are:
Stack At BottomThe group footer section is rendered at bottom of the current page,
provided that an inner group having this value would force outer group footers to
stack at the bottom of the current page, regardless of the outer group footer setting.
Force At BottomThe group footer section is rendered at bottom of the current page,
provided that an inner group having this value would render its footer right at the
bottom of the page, forcing the outer group footers to render on the next page.
Collate At BottomThe group footer section is rendered at bottom of the current
page, provided that the outer footers have a similar footer display option to render
at the page bottom as well, because otherwise, they cannot be forced to change
their behavior in any way.
Keep Together This flag is used to prevent the group from splitting across two pages or columns,
but only on the first break attempt.
Fonts and Styles
125
CHAPTER 8FONTS AND STYLES
Fonts describe the features (shape and dimension) of text characters. In JasperReports, you can specify the font properties for
each text element.
You can save time defining the look of your elements, included all the font settings, by using styles. A style is a collection of
pre-defined properties that refer to aspects of elements (like background color, borders, and font). Instead of continually
selecting individual settings, you can define a default style for your report and all undefined properties of your elements will
refer to it.
This chapter has the following sections:
Working with Fonts
Using TrueType Fonts
Character Encoding
Use of Unicode Characters
Working with Styles
Creating Style Conditions
8.1 Working with Fonts
Usually a font is defined by the following basic characteristics:
Font name (font family)
Font dimension
Attributes (bold, italics, underline, strikethrough)
If you plan to export a report as a PDF file, JasperReports requires the following additional information:
If the report is not exported to PDF format, the font the report engine uses is the one specified by the font name and enriched
with the specified attributes. In the case of a PDF document, the PDF font name identifies the font used. The report engine
PDF font name The name of the font (it could be a pre-defined PDF font or the name of a TTF file
present in the classpath)
PDF embedded A flag that specifies whether an external TrueType font (TTF) file should be included
in the PDF file
PDF encoding A string that specifies the name of the character encoding
126
iReport Ultimate Guide
ignores the Bold and Italics attributes when exporting a report as a PDF, since these particular characteristics are part of the
font itself and cannot be overridden. If you look at the list of pre-defined PDF fonts you will see something like this:
Helvetica
Helvetica-Bold
Helvetica-BoldOblique
Helvetica-Oblique
...
So, for example, if your report includes text formatted in Helvetica and the textfield must be rendered in bold, you have to
choose the Helvetica-Bold font. You will also see that some attributes, such as underline and strikethrough, do not exist as
separate font names because they are built into all fonts.
8.2 Using TrueType Fonts
You can use an external TrueType font. To do so, the external fonts (files with .ttf extensions) must appear in the classpath.
Note that any TrueType fonts you use must be available as you design the report in iReport and whenever the JasperReports
report engine generates an instance of the report, such as when a servlet or Java or Swing program prints a version. This simple
way to use True Type font has been actually deprecated. If you are using True Type fonts, you are probably exporting your
report in PDF and probably your requirement is to embed the custom font inside your documents. To do that, there are specific
PDF-related properties for the text elements in JasperReports, but all of them has been deprecated since version 3.6.2. The best
solution is to use a Font Extension, a kind of JasperReports plug-in to deploy the fonts you are using in your application. The
font extensions are explained later in this chapter. For now, let’s continue to explore the old way to use a TrueType font.
In the Font name combo box in the property sheet for static and textfields, only the font families available as extensions and
the system fonts, managed by the Java Virtual Machine (JVM), are shown (see Figure 8-1). These are usually inherited by the
operating system. Therefore, you must install an external TrueType font on your system before use it in non-PDF reports or
better create a font extension for it.
The Font name property can be freely edited. If the specified font name is not found, JasperReports will use the default font
instead (which is an open source font called DejaVu).
Figure 8-1 System fonts Figure 8-2 PDF font names
Fonts and Styles
127
The list of available PDF Font names is compiled from the set of built-in PDF fonts and the list of the TrueType fonts found in
the font paths (each item is presented with the font name and the name of the TrueType font to which it refers). You can set the
font paths in the Options dialog.
In general, JasperReports (the report engine) looks for fonts in the classpath. Since scanning the entire classpath for all the
available fonts can significantly delay report generation, iReport uses a subset of the classpath paths when looking for fonts.
To set the fonts paths, add them to the classpath first (see the Classpath tab in the Options dialog), then check them in the
Fontpath tab.
If you need to use a TrueType font that is not available when you are designing your report, edit the TTF file name directly in
the combo box. Please note that if the file is not found when the report is run, an error will result when you export it as a PDF.
If the selected font is an external TTF font, to ensure that the font is viewed correctly in the exported PDF document, select the
PDF Embedded check box.This forces the report engine to include the required fonts as metadata in the PDF file (but note that
it increases the document size).
8.3 Using the Font Extensions
As we hinted in the previous chapter, the best way to define and use a font in JasperReports is to create and use a font
extension. Support for font extensions was introduced in iReport 3.6.2 even though it was available in JasperReports for a long
time before. The aim of a font extension it to be sure that a text element that uses a particular font family is rendered in the
same way on different systems. This is not obvious. In particular, the Java virtual machine can map different logical font
family names to different physical fonts. This can lead, for instance, to losing parts of the text in a text element that has been
Figure 8-3 Font paths in the Options dialog
Avoid adding hundreds of TrueType fonts to the fontpath because they slow down iReport’s startup. For Windows in
particular, avoid adding the %WINDIR%\fonts directory to the fontpath.
128
iReport Ultimate Guide
designed for a specific font on a specific platform. On other platforms, the same font might be rendered differently or it might
not be available at all.
There are then other advantages mainly when working with PDF files: when using an extensions, is no longer required to set
the font to use when the report is exported in PDF (note that the font specified in the property font name is not the same font
used when the report is exported in PDF), the bold and italic fonts can be specified inside the extension and finally there is no
longer needed to set the text encoding of a particular text element. All these information are defined inside the font extension.
The idea behind a font extension is to force JasperReports to work with True Type fonts instead of using built-in or system
fonts. This assures that a specific font behaves in the same way wherever the report is executed. Font extensions can be created
in the Options panel of iReport (Tools Options) in the Fonts tab (Figure 8-4). What you need it a TrueType font file (and,
depending on the font and its font styles, or typefaces, files containing the corresponding bold, italic, and bold-italic versions
of the font).
By clicking Install Font it is possible to create a font extension managed internally by iReport. This font extension can be
modified and exported to a JAR to be used in other applications.
1. Once you have clicked Install Font, the Font Installation wizard pops up. In the first step, specify the main TrueType font
file (Figure 8-5).
Figure 8-4 Font extensions
Fonts and Styles
129
2. Click Next.
iReport reads the font and selects the font’s family name that is embedded in the TTF file (Figure 8-6). This name is the
logical name used by JasperReports and it is arbitrary. When JasperReports renders a text element, if the font name
property is set, it looks for a font extension corresponding to the font name. If an extension is found, JasperReports
renders the text. If an extension is not found, the font name will be treated as a system font name and the Java Virtual
Machine will be responsible for providing the correct font.
In this step it is also possible to specify the TTF files for the bold, italic and bold italic versions of the font. Professional
fonts usually have all these four TTF files (normal, bold, italic, bold-italic).
Finally, it is possible to specify the encoding of the font (this depends by which characters the font contains) and whether
the font should be embedded in the PDF documents (which is strongly suggested for custom fonts).
Figure 8-5 Font Extension Wizard - Font selection
130
iReport Ultimate Guide
Additional options are available for advanced users and those with special font requirements.
1. You can specify the locales for which the extension is valid (Figure 8-7).
Figure 8-6 Font Extension Wizard - Family Details
Fonts and Styles
131
For example, you can define an extension for the family MyFontFamily that is valid only for Latin languages, and another
extension with the same font family name that is valid for Asian languages that may require special glyphs usually not
available in the TTF files. Leave the list empty if the font can be used with any languages.
2. The final step (Figure 8-8) can be used to define the font family’s font names to be used by the HTML and RTF
exporters.
Suppose we are exporting to an HTML document a report having a text element with font name MyFontFamily. The font
MyFontFamily cannot be recognized by a browser since it does not refer to a known system font, and the TTF file of the
extension cannot be used by the browser. So we set the name of a replacement font that can be used instead, such as
”Arial.” For HTML, we can set more than one name, such as “Verdana, Arial.” The order of the font names indicates the
order in which the web browser should search for the replacement font. Once a replacement font is found, the browser
stops searching and renders the text.
Figure 8-7 Font Extension Wizard - Locales
132
iReport Ultimate Guide
When the extension has been completed, iReport installs it. The new extension becomes visible in the fonts list in the Options
panel (Figure 8-9), and it is added to the font combo box in the Text tool bar (Figure 8-10).
Figure 8-8 Font Extension Wizard - Font Mappings
Figure 8-9 Font Extension Wizard - Family Details
Fonts and Styles
133
By clicking Export as extension, it is possible to export one or more font families and create JasperReports extensions
automatically (in the form of a JAR that must be added to the classpath of your application).
If you already have a font extension, you can install it by adding the JAR to the iReport classpath.
8.4 Character Encoding
Correct character encoding is crucial in JasperReports, particularly when you have to print in PDF format. Therefore, it is very
important to choose the right PDF encoding. The encoding specifies how characters are to be interpreted. In Italian, for
example, to print correctly accented characters (such as è, ò, a, and ù), you must use CP1252 encoding (Western European
ANSI, also known as WinAnsi). iReport provides an extensive set of pre-defined encoding types in the PDF Encoding combo
box in the Font tab of the element properties window.
If you have problems with reports containing non-standard characters in PDF format, make sure that all the fields have the
same encoding type and check the charset used by the database from which the report data is read.
8.5 Use of Unicode Characters
You can use Unicode syntax to write non-Latin-based characters (such as Greek, Cyrillic, and Asian characters). For these
characters, specify the Unicode code in the expression that identifies the field text. For example, to print the Euro symbol, use
the Unicode \u20ac character escape.
8.6 Working with Styles
The Report Inspector displays the available styles in the outline view, in the node labeled Styles. To create a new style, right-
click the Styles node and select Add style from the contextual menu (see Figure 8-11).
Figure 8-10 The new font family available in the Fonts combo box
The expression \u20ac is not simple text; it is a Java expression that identifies a string containing the € character. If
you write this text into a static text element, “\u20ac” will appear; the value of a static field is not interpreted as a Java
(or other language) expression (this only happens with the textfields where the context is provided using an
expression).
134
iReport Ultimate Guide
You can define many properties for a style, which are then shown in the property sheet (Figure 8-12). The only property value
of a style that must be set is Name. All other properties are optional.
Leave the default value as-is when you don’t want to set a specific value for a property. To restore a default value, right-click
the property name and select Reset to default value. (This works with all the element properties that support a default value.)
Figure 8-11 Adding a new style to the document
Figure 8-12 All the properties of a style
Fonts and Styles
135
To apply a style to an element, select the element and set the desired style in the property sheet (Figure 8-13).
You can choose a specific style to be the default style for your report. When setting a default style, all the element properties
having an unspecified value will implicitly inherit their value from the default style. The Parent style property defines the style
from which the current one inherits default properties.
The remaining properties fall into the following four categories:
Common properties
Graphics properties
Border and padding properties
Text properties
For details about the properties, refer to Chapter 5.
8.7 Creating Style Conditions
You can design your report so that a style changes dynamically. For example, you can set the foreground color of a textfield to
black if a particular value is positive and red when it is negative. iReport creates conditional styles as deriving from an existing
style, for which we set the condition and change some properties.
To apply a condition to a style, right-click the style node and select Add Conditional Style (see Figure 8-14).
You can reconfigure all the values of the parent style. The new values will be used instead of the ones defined in the parent
when the condition is true. The new conditional style will appear in the outline view. You need to set the condition (actually an
expression that returns a Boolean value) that will be evaluated during the rendering of elements that use the style.
In the condition expression you can use all the properties of the report object. Please note that the conditions cannot be generic,
for instance, you cannot set a condition like “if the number is positive” or “if the string is null.” You must be very specific,
specifying, for example, that a particular value (field, parameter, variable or any expression involving them) must be positive
or null, and so on.
Figure 8-13 Style property of an element
Figure 8-14 Setting a conditional style
136
iReport Ultimate Guide
A style can have an arbitrary number of conditional styles. A good example of this would be designing your report to display a
particular field in a different color (let’s say depending on the total number of orders placed). You would set the foreground
color as red in the base style, then add a conditional style to be used when the variable $V{total_orders} is less that 5 for
which the color would be red, another conditional style with the foreground color set to yellow when the same value is
between 6 and 10, and green for another conditional style for a number of order greater than 20.
Let’s see an example of using a conditional style to achieve the effect of having an alternating background for each row. The
effect is shown in Figure 8-15.
The trick is pretty simple. The first step is to add a frame element in the Detail band. The frame will contain all the elements of
the band, so we are using the frame as if it were the background for the band itself; in fact, the frame should take all the space
available in the band. Then all the textfields will be placed inside the frame (see Figure 8-16 and Figure 8-17).
Figure 8-16 does not reflect the real design, I just tried to project the idea that the textfields showing the real data are inside a
the frame that covers the entire surface of the band.
Figure 8-15 Alternated color for each row
Figure 8-16 All the elements are placed inside the frame
Fonts and Styles
137
This should be particularly clear looking at the outline view (Figure 8-17).
First we define a new style (let’s call it Style1). We will keep all the default values, since we are not interested in changing
them when the row number is odd (1, 3, 5, etc...). Now we add a conditional style and set as the condition the expression:
($V{REPORT_COUNT} % 2) == 0
Remember, we have been using Groovy or JavaScript as the report language. In Java the expression would be a bit more
complicated; for example:
($V{REPORT_COUNT}.intValue() % 2) == 0
What the expression does is calculate the rest of the set by 2 (the operator % has this function). We need to see if the remainder
is 0. If it is, the current row number (held by the REPORT_COUNT built-in variable) is even, we use the conditional style Style1.
For this style, we set the background property to a light gray (or any other color of our choice) and the opaque property to true
(otherwise the previous property will not take effect). Finally, we apply the style to the frame element by selecting the frame
and setting the style property to Style1.
Run the report. The results should be exactly what is presented in Figure 8-15.
8.8 Referencing Styles in External Property Sheets
Often you will want to use the same styles in multiple reports. You can create a property sheet for each style in a JRTX file and
reference the file in all the reports, rather than define the style in every report separately. Using the referenced file, you can
apply style changes across all the reports and insure that the reports have the same properties.
To create a style property sheet in a JRTX file:
1. In the main menu, click New and select an empty report.
2. Select File New.
3. Select Style from the left side of the New File panel.
4. Click the Finish button.
5. Enter a name and location for the new JRTX file.
For best performance, save the file locally rather than on a shared or network drive.
Note that the template file extension is .jrtx.
6. Click Finish.
7. Select New Style in the Template Inspector.
8. In the Property panel, set the properties of the style (see Figure 8-12).
9. Save the style.
10. Create and save as many additional styles as you need.
Figure 8-17 The outline view shows the elements hierarchy
138
iReport Ultimate Guide
11. Save the template.
12. Close the report.
To apply styles from a JRTX file:
1. Open the report that will use the styles.
2. In the Report Inspector, right-click Styles and select Add Style reference.
3. In the file window that opens, select the template file.
The template’s styles should now appear in the Report Inspector.
4. Apply the styles to the report.
5. Save the report.
Templates
139
CHAPTER 9TEMPLATES
One of the most useful tools of iReport is the Template Chooser (Figure 9-1), from which the user can pick a template, a kind
of pre-built report. Templates can be used as the base for new reports with no further changes, and they can be used as a model
to which fields, textfields and groups can be added in the Report Wizard.
When the Template Chooser pops up, it scans the directory <ireport home>/ireport/templates, looking for JRXML files. In
addition, all the paths specified in the options as template directories or as template files are scanned in the same way. The
valid JRXML files found are proposed as possible templates. If a template provides a preview image, it is used in the file
chooser.
Figure 9-1 Template chooser
140
iReport Ultimate Guide
In this chapter, I will explain how to build a custom template that works well with the wizard as well as how to add new
templates to the ones already available so that they appear in the Template Chooser.
This chapter has the following sections:
Template Structure Overview
Groups
Column Header
Detail Band
Template Type and Other Options
Creating a New Template
Installing and Using the Template
9.1 Template Structure Overview
A template is a normal JRXML file. When a new report is created using the Report Wizard, the JRXML file of the selected
template is loaded and modified according to the options you have specified in the wizard steps. If the user chooses not to use
the wizard, the selected template is just copied along with all the referenced images in the location the user has specified.
In general, a template does not require special formatting or structure, especially if it is meant to be used only as the starting
point for a new report. However, with a little effort, we can provide templates that can be used by the wizard in really
productive ways.
The Report Wizard is able to create from a list of fields (selected by the user during the wizard steps) two types of reports,.
Even better, it is able to populate a template adding textfields and labels, organizing them in two ways: columnar and tabular.
The former is realized by adding two elements to each field in the record: a static text which is used as the label for the field
and displays the field name plus a textfield that displays the field value (Figure 9-2). The result is that for each record we get
a column with the names of the fields and a column with their values. All are placed in the Detail band. Notice that the Column
Header band is not used at all.
Templates
141
A tabular type shows all records in a table-like view (Figure 9-3).
Figure 9-2 Columnar report
142
iReport Ultimate Guide
The labels for the field values are placed in the Column Header band, while for each field in the record, a textfield is placed in
the Detail band. The result is a column header showing the value names and, in the Detail band, many rows, one for each
record, showing the record data.
When the user chooses to group the data using the wizard step shown in Figure 9-4, the wizard creates all the necessary report
structures to produce the requested groups. The Report Wizard permits the creation of up to four groups, and a group header
and group footer is associated with each group. If the template defines one or more groups and the user requested to group the
data, the wizard tries to use the existing groups before creating new ones. By default, groups in the template are deleted if they
are not used. For each group, the wizard sets the group expression and adds a label for the name and a textfield showing the
value of the group expression (which is always a field name, since the grouping criteria set using the wizard is one of the
selected fields).
Figure 9-3 Tabular report
Templates
143
Summarizing, a template is a JRXML file with, optionally, some images. It can be used with no further changes when creating
a new file. If used with the Report Wizard, the wizard is able to modify the template adding field definitions, labels, and
textfields organized in a columnar or tabular way (if nothing is specified, the tabular format is used by default) as well as
groups.
Let’s see how to design a template to leverage the wizard capabilities by analyzing an old template file called classicC.jrxml.
This template is no longer shipped with iReport—it has been replaced by new templates—but given its basic graphic, it is
perfect for illustrating how a template should be structured.
The file is shown in Figure 9-5. It contains four groups: Group1, Group2, Group3, and Group4, for which the Group Header
and the Group Footer bands are visible.
Figure 9-4 Group by step in Report Wizard
144
iReport Ultimate Guide
The Column Header band is hidden because this is a columnar report and the band is not useful, while in the Detail band there
are static text labels and textfields. Some elements (like the one in the title that shows the template name or the one in the page
footer that shows the page number) are ignored by the wizard which will not modify them. As well, there are some labels and
textfields which contain a special keyword as text. These will be used by the wizard as templates to create new fields or
populated with proper expressions to show specific data. Here are the rules to follow to specify how the wizard will work with
these elements.
And here is the corresponding tabular report format.
9.2 Groups
We have said the wizard uses up to four groups. They are used in order from first last, respecting the group order defined in the
report. For example. if the user decides to group the data by COUNTRY, and this is the only group requested, the wizard will
use only Group1 (the one that is all black in the illustration 5). If the user decides to have to levels of group, let’s say
COUNTRY and CITY, the wizard will use Group1 for the COUNTRY and the nested Group2 for the CITY.
The group header and footer can contain any arbitrary element.
Figure 9-5 classicC.jrxml report
Figure 9-6 classicT.jrxml report
Templates
145
If a static text element is present in a group header and it contains one of the following strings, the value of the label is set to
the name of the field selected in the wizard as criterion for the group (that is, COUNTRY):
GroupLabel
Group Label
Label
Group name
GnLabel (where n in the last string represents the group number)
If a textfield element is present in a group header and it contains one of the following expressions, the textfield is set to the
field selected in the wizard as criterion for the group (that is, $F{COUNTRY}):
“GroupField”
“Group Field”
“Field”
“GnField” (where n in the last string represents the group number)
Please note that all the expressions are accepted with or without the apices (for compatibility with the old templates). If the
apices are omitted, you get an invalid Java expression which indicates that the report did not compile correctly. I suggest you
always use the apices so you can preview your template without problems while designing it, which is extremely useful.
9.3 Column Header
The Column Header band is analyzed by the wizard when the report is tabular, which is the default format used by the wizard.
In the illustration 6 there is another old template, very similar to the ClassicC we have see in the figure 5, called ClassicT (“T”
stands for Tabular). It contains a Column Header band composed of a frame element (the gray portion) and a static text with
the value DetailLabel. This is the static text the wizard will look for in order to create a label for each field. In particular, the
wizard will look for a static text with one of the following strings:
DetailLabel
Label
Header
If such static text is found, the label text is replaced with the name of the field that will be shown in the Detail band at the same
position.
9.4 Detail Band
Finally, the Detail band. If the report is meant to be tabular, the wizard will look for a textfield with one of the following
expressions:
“DetailField”
“Field”
If such a textfield is found, its expression is set to the proper field (that is, $F{ORDER_ID}).
If the report template is columnar, the wizard will look in the Detail band for a static text with the same criteria described for
the column header.
The Report Wizard replicates the Detail Label and the Detail Field, creating as many static text/textfield pairs as there are in
the report’s selected fields, except for the fields used in the groups.
All the other bands can contain whatever elements you desire; the wizard will ignore them.
9.5 Template Type and Other Options
We have not said yet how to force the wizard to produce a columnar layout instead of a tabular one. This can be done by
adding to the report template the report property template.type. The possible values for this property are tabular and
columnar.
146
iReport Ultimate Guide
To force the wizard to keep unused groups, just set the property template.keepExtraGroups to true.
9.6 Creating a New Template
Let’s see how to create and use a custom template from scratch, starting from an empty report. In this sample, we will create a
tabular template called sample_template.jrxml. The name of the file will be used as the name of the template in the Report
Wizard. Once we create the new report, we will add to it four groups named, Group1, Group2, Group3, and Group4, and we
will add header and footer bands. The group names can be arbitrary, but it’s good practice in template design to set a number.
First, we’ll create the JRXML file. In the main menu, click New... and select an empty report. To create a group, right-click the
report root node in the Report Inspector and click Add Report Group. The group expression can be empty; the wizard will set
a proper value for it if one is required. Figure 9-7 shows a simple design with the four groups.
It’s time to add the required template elements to the Group Header and Detail bands. Add a label element in all the group
headers, setting a text Label and a textfield element with the expression Field. In Figure 9-8, the labels and the textfield
use the syntax GnLabel and “GnField”. The template we are working on is a tabular type, so we need to provide a label
element in the column header and a textfield in the Detail band (with the text DetailLabel and the expression
“DetailField”, respectively).
Figure 9-7 Empty report with four groups
Templates
147
The mandatory part is done now, so you can proceed to adding some graphics to achieve a complete template.
9.7 Installing and Using the Template
Now that we created the JRXML for the new template, we have to add it to the list of available templates. Click Tools
Options, go to the iReport section, and select the Wizard Templates tab. On the tab, add the new file (Figure 9-9).
Figure 9-8 Your custom template
148
iReport Ultimate Guide
A final option is to put your template in the templates directory of iReport.
Let’s try the new template by creating a file. The new template appears in the Template Chooser.
Figure 9-9 New template added to list in wizard
Templates
149
Select the new template (simple_template) and launch the wizard, following the steps for creating a new report (2.10,
“Creating Your First Report,” on page 25). To test the template properly, you should use all the groups in the wizard.
Figure 9-10 New template in Template Chooser
150
iReport Ultimate Guide
Figure 9-11 shows the report that results:
If the result is correct, we can produce an image to be used as a preview (PNG or GIF format). This is really simple. Preview
the report as in 2.10.2, “Using the Report Wizard,” on page 25. Then, in preview mode (Figure 9-12), click the Preview
button to save the image of the current page.
The image must be saved in the same directory as the template and it must be given the same name as the template (plus the
extension .png or .gif). Opening the Template Chooser again, you should see the preview image of your template.
If you develop a nice template and you want to share it with the iReport community, save it as a patch on the iReport web site.
Figure 9-11 Report created from new template
Templates
151
Figure 9-12 Preview of report created from new template
152
iReport Ultimate Guide
Data Sources and Query Executers
153
CHAPTER 10 DATA SOURCES AND QUERY EXECUTERS
There are several ways that JasperReports can provide data to fill a report. For example, you can put an SQL query directly
inside a report and provide a connection to a database against which to execute the query and read the resulting record set, or
you can use a more sophisticated custom technology to provide a table-like set of values.
iReport provides direct support for a rich set of query languages, including SQL, HQL, EJBQL, and MDX, and supports other
languages like XPath (XML Path Language). Moreover, in iReport, you can use custom languages by registering plug-in
engines called query executors to interpret and execute the report query.
If you don’t want to use a query language, or you simply don’t want to put the query inside a report, you can use a
JasperReports data source. Basically, a JR data source is an object that iterates on a record set that is organized like a simple
table.
All the data sources implement the JRDataSource interface. JasperReports provides many ready-to-use implementations of
data sources to wrap generic data structures, like arrays or collections of JavaBeans, result sets, table models, CSV and XML
files, and so on. In this chapter I will present some of these data sources, and you will see how easy it is to create a custom data
source to fit any possible need. Finally, you will see how to define a custom query language and a custom query executor, as
well as how to use them.
iReport provides support for all these things: you can define JDBC (Java Database Connectivity) connections to execute SQL
queries, set up Hibernate connections using Spring, and test your own JRDataSource or your custom query language.
This chapter has the following sections:
How a JasperReports Data Source Works
Understanding Data Sources and Connections in iReport
Creating and Using JDBC Connections
Working with Your JDBC Connection
Understanding the JRDataSource Interface
Data Source Types
Importing and Exporting Data Sources
10.1 How a JasperReports Data Source Works
JasperReports is a records-based engine; to print a report, you have to provide a set of records. When the report runs,
JasperReports will iterate on this record set, creating and filling the bands according to the report definition. Bands, groups,
variables—their elaboration is strictly tied to the record set used to fill the report. This is why JasperReports defines only one
query per report. However, multiple queries/data sources can be used when inserting subreports or defining subdatasets. Each
154
iReport Ultimate Guide
one will have its own query (or data source), fields, parameters, variables, and so on. Subdatasets are only used to feed a
crosstab or a chart.
Each record is a set of fields. These fields must be declared in the report in order to be used, as explained in Chapter 6. But
what is the difference between using a query inside a report and providing data using a JRDataSource?
Basically, there is no difference. In fact, what happens behind the scenes when iReport uses a query instead of a
JRDataSource is that JasperReports executes the query using a built-in or user-defined query executor that will produce a
JRDataSource. There are circumstances when providing a JDBC connection to the engine and using a query defined at
report level can simplify the use of subreports.
A JRDataSource is a consumable object, which means that you cannot use the same instance of JRDataSource to fill more
than one report or subreport. A typical error is trying to use the same JRDataSource object (for example, one provided to the
report as a parameter) to feed a subreport placed in the Detail band. If the Detail band is printed more than once (and normally
it is printed for every record present in the main data source), the subreport will be filled for each main record, and every time
the subreport will iterate on the same JRDataSource. This will give results only the first time the data source is used.
At the end of this chapter, you will know how to avoid this kind of error, and you’ll have all the tools you need in order to
decide the best way to fill your report with any of these:
A query in a language supported by JasperReports.
A built-in data source.
A custom data source.
A custom query language with the relative query executor.
10.2 Understanding Data Sources and Connections in iReport
iReport allows you to manage and configure different types of data sources to fill reports. These data sources are stored in the
iReport configuration and activated when needed.
When I talk about data sources, you need to understand there is a distinction between real data sources (or objects that
implement the JRDataSource interface) and connections, used in combination with a query that is defined inside the report.
In addition, the term “data source” used in JasperReports is not the same as the concept in javax.sql.Datasource, which is
only a means of getting a physical connection to the database (usually with JNDI the lookup). The data source object I refer to
in the JasperReports realm contains concrete data.
Here is a list of the data source and connection types provided by iReport:
JDBC connection
JavaBean collection data source
XML data source
CSV data source
Hibernate connection
Spring-loaded Hibernate connection
Hadoop Hive data source
JRDataSourceProvider
Custom data source
Mondrian OLAP connection
XMLA connection
EJBQL connection
Empty data source
Finally, there is a special mode to execute a report, called query executor mode, that you can use to force the report’s creation
without passing any connection or data source to the report engine.
All the connections are “opened” and passed directly to JasperReports during report generation. For many connections,
JasperReports provides one or more built-in parameters that can be used inside the report for several purposes (for example, to
fill a subreport that needs the same connection as the parent).
Data Sources and Query Executers
155
The XML data source allows you to take data from an XML document.
A CSV (comma-separated values) data source allows you to open a CSV file for use in a report.
The JavaBean set data source, custom data source, and JRDataSourceProvider allow you to print data using purposely
written Java classes.
The Hibernate connection provides the environment to execute HQL (Hibernate Query Language) queries (this
connection can be configured using Spring, as well).
EJBQL (Enterprise JavaBean Query Language) queries can be used with an EJBQL connection.
MDX queries can be used with a native direct connection to a Mondrian server or using the standard XML/A interface to
interrogate a generic OLAP database.
An empty data source is something like a generator of records having zero fields. This kind of data source is used for test
purposes or to achieve very particular needs (like static content reports or subreports).
Connections and data sources are managed through the menu command Tools > Report Datasources, which opens the
configured connections list (Figure 10-1). To set up a new data source, you can also click the Report Datasources button on
the toolbar.
Even if you keep an arbitrary number of data sources ready to use, iReport works always with only one source at a time. You
can set the active data source in several ways. The easiest and most intuitive way is to select the data source from the combo
box located on the tool bar. (see Figure 10-2). You can also set the active data source by selecting a data source in the
Connections/Datasources dialog box and clicking the Set as default button.
Figure 10-1 Report Data Sources dialog
As mentioned previously, a connection and a data source are different objects. However, from this point on, I will use
these two words interchangeably because their functions are so similar.
156
iReport Ultimate Guide
If no data source is selected, it is not possible to fill a report with data, therefore, when iReport starts for the first time, a pre-
configured empty data source is defined and selected by default. Datasources can be used in conjunction with the Report
Wizard, too. That’s why configuring the connection to your data is usually the first step when starting with iReport.
10.3 Creating and Using JDBC Connections
A JDBC connection allows you to use a relational DBMS (or, in general, whatever databases are accessible through a JDBC
driver) as a data source. To set a new JDBC connection, click the New button in the Connections/Datasources dialog box
(shown earlier in Figure 10-1) to open the interface for creation of a new connection (or data source). From the list, select
Database JDBC connection to bring up the window shown in Figure 10-3.
Figure 10-2 The data sources combo box shows the active data source
Data Sources and Query Executers
157
The first thing to do is to name the connection (possibly using a significant name, such as Mysql – Test). iReport will
always use the specified name to refer to this connection.
In the JDBC Driver field, you specify the name of the JDBC driver to use for the connection to the database. The combo box
proposes the names of the most common JDBC drivers (see Figure 10-4).
If a driver is displayed in red, the JDBC driver class for that driver is not present in the classpath and it is not possible to use it.
See Chapter 10.3.4, “Creating a JDBC Connection via the Services View,” on page 159 for how to install a JDBC driver.
Thanks to the JDBC URL Wizard, it is possible to automatically construct the JDBC URL to use the connection to the
database by inserting the server name and the database name in the correct text fields. Click the Wizard button to create the
URL.
Figure 10-3 Configuring a JDBC connection
Figure 10-4 JDBC drivers list
158
iReport Ultimate Guide
Enter a username and password to access the database. By means of a check box option, you can save the password for the
connection.
If the password is empty, it is better if you specify that it be saved.
After you have inserted all the data, it is possible to verify the connection by clicking the Test button. If everything is okay, the
dialog box shown in Figure 10-5 will appear.
When you create a new data source, iReport sets it as the active one automatically for your convenience.
In general, the test can fail for a lot of reasons, the most frequent of which are the following:
A ClassNotFoundError was thrown.
The URL is not correct.
Parameters are not correct for the connection (database is not found, the username or password is wrong, etc.).
Let’s take a closer look at these issues.
10.3.1 ClassNotFoundError
The ClassNotFoundError exception occurs when the required JDBC driver is not present in the classpath. For example,
suppose you wish to create a connection to an Oracle database. iReport has no driver for this database, but you could be
deceived by the presence of the oracle.jdbc.driver.OracleDriver driver in the JDBC drivers list shown in the window
for creating new connections. If you