Вы находитесь на странице: 1из 31

Manual for iReport >= 0.2.

0 (pure java version of iReport)


1 General Information about iReport o 1.1 What is iReport o 1.2 Short history of iReport o 1.3 Books about JasperReports o 1.4 The main features of iReport o 1.5 Useful JasperReports and iReport related links

2 Installing iReport o 2.1 System Requirements o 2.2 Installation and configuration o 2.3 The final test...

3 iReport and JasperReports basic concepts o 3.1 How JasperReports works o 3.2 Compilation end export of reports o 3.3 Our first very simple report

4 Connections and Datasources o 4.1 Types of datasource o 4.2 Setting up a JDB C connection o 4.3 Setting up a custom datasource o 4.4 Implementing a new custom datasource

5 Bands and groups o 5.1 Bands o 5.2 Groups

6 iReport plugins o 6.1 The abstract iReport plugin o 6.2 The plugin file descriptor o 6.3 The hello world plugin

7 Using the XML datasource o 7.1 Configuring an XML datasource o 7.2 The Record Path o 7.3 XML Dat asource Syntax o 7.4 Addressbook sample o 7.5 XML Dat asource license

8 Charts o 8.1 Creation of a simple chart

1 General Information about iReport


This is the iReport reference manual; it documents iReport version 0.3.1. As iReport is work in progress, the manual gets updated frequently (if I have sufficent time). So there is a very good chance that this version is out of date, unless you are looking at it on-line. The most recent version of this manual is available at http://ireport.sourceforge.net/docs.html in many different formats. iReport is a powerful, intuitive and easy to use visual report designer/builder for JasperReports. iReport is free software. It is licensed with the GNU GENERAL PUBLIC LICENSE http://www.gnu.org/ .

If you want purchase a LGPL style licence for iReport, you can contact me at gt(@)businesslogic.it.
IMPORTANT: Reports of bugs, as well as questions and comments should be sent to iReport forums at http://sourceforge.net/forum/?group_id=64348

1.1 What is iReport


iReport is a program that helps users and developers that use JasperReports library to visually design reports. Throught a rich and very simple to use GUI, iReport provide all the most importatnt functions to create nice reports in a little time. iReport can help people that don't know JasperReports library to create complex reports and learn the XML syntax taking a look to the generated code. iReport can help skilled report designer to compose very complex page saving a lot of time. iReport is written in java. From the version 0.2.0 it was totally rewrited. For this reason they are two manuals for iReport. The new development direction was taken for a lot of reasons. iReport has lost a bit of efficence leaving the win32 native GUI for a clear, pure swing interface. But this is the right direction...

1.2 Short history of iReport


iReport is a visual designer for JasperReports. But What's JasperReports? JasperReports is the best (IMHO) open source reporting engine available for java community. It is developed by a small big genius called Teodor Danciu. JasperReports has always had one lack: it don't provide an adapted tool to visually desing reports. JasperReports has hundred of features, possibilities of use are infinitely... a person that does not have much confidence with the XML could have some problems to take fully advantage from the jasperreports library . So in little time are borned some tools to fill the design hole... in order: Designer for Jasper by Jackie Manning and JasperEdit and Jeez by Erik Swenson, the first an editor capable to preview JasperReports XML and the second an Eclipse plugin. In the same period, I was trying DataVision, a tool by Jim Menard. So my idea was join the powerful of Jasperreports with the philosophy adopted by DataVision. I solved the problem of a slow java interface using... VisualJ++. The result was one of the best visual designer for JasperReports. After six months, I posted a message on JasperReports forum about the idea to develop a pure java version of iRe port. The enthusiasm was such that the same day I began the porting... iReport for java is now a reality.

1.3 Books about JasperReports


The mission of this manual is to introduce you in the world of JasperReports. However I suggest you to buy for few dollars the JasperReports Ultimate Guide, a fundamental manual to write jasperreports XML code (via iReport or directly to hand). You can find JasperReports Ultimate Guide at http://jasperreports.sourceforge.net/more.docs.html .

1.4 The main features of iReport

The following list describes some of the important characteristics of iReport: 98% of JasperReports tags supported Visual designer wysiwyg with tools for draw rectangles, lines, ellipses, textfields fields, charts, subreports... Builtin editor with syntax heighlighting for write expression Support for unicode and non latin language (russian, chinese, korean,...) Document structure browser Integrated compiler and exporter Support of all JDBC compliant databases Support of all kind of JRDataSource Wizard to create automagically reports Support for subreports Save backup Support for templates Facilities for fonts

1.5 Useful JasperReports and iReport related links


JasperReports home page iReport home page iText home page The pdf library used by JasperReports

2 Installing iReport
iReport comes as a zip archive. It contains the main distribution files (classes and source), some templates for wizard, all additional required jars. <="" font=""> 2.1 System Requirements You'll need several things to get started with iReport: Sun JDK 1.4 or greater Ant (required if you want recompile sources, but strongly reccomended to lunch iReport too) JasperReports 0.4.6 (*) SAX 2.0 XML Parser (Apache Xerces 1.3 or later recommended) (*) Jakarta Commons Digester Component (version 1.1 or later) (*) Jakarta Commons BeanUtils Component (version 1.1 or later) (*) Jakarta Commons Collections Component (version 1.0 or later) (*) Jakarta Commons Logging Component (version 1.0 or later) (*) JDBC 2.0 Driver (A MySql driver is already included) (*) iText - Free Java-PDF library b y Bruno Lowagie and Paulo Soares (*) Jakarta POI (version 1.5.1 or later) (*) JFreeChart (version 0.9.8 or later) (*) Acrobat Reader 5.0 is not required, but strongly recommended. If you think to use Chinese Simplified, Chinese traditional, Japanese and Korean characters, you must download the Asian font pack from Adobe at:http://www.adobe.com/products/acrobat/acrrasianfontpack.html or use a localized Windows. If you want connect to a database, you must provide a JDBC driver (not shipped with iReport).

(*) a jar of this software is already included in the lib directory of iReport distribution, so you have not to download it. Note that for now JFreeChart is used to generate charts. This can be change. I'm evaluating JCharts, another OpenSource charting library. It's possible that in future iReport will support both this libraries trought an abstract layer.

2.2 Installation and configuration


If you have already installedon your machine a jdk (not simply a Java Runtime Enviroment, but a Java Development Kit) we are ready to start... 1. Unzip iReport-x.x.x.zip and copy the e xtracted directory where you want. 2. Look for a file called tools.jar in your jdk and copy it in the lib directory of iReport. If you have Ant installed on your machine, modify the file iReport.bat or iReport.sh to adjust the ant installation path (default is c:\ant under Win32 and /ant under Linux). 3.Start iReport.bat or iReport.sh. If you don't have Ant installed (olny for win32 users), go to the directory noAnt and type:

startup.bat
At the first execution, iReport will create a directory (.ireport) in your home directory. Here will be stored all configuration files. iReport use XML files for configuration. ***This files are not compatible with old 0.1.0 properties files***. At startup all jars in the iReport lib directory are added to the classpath. If you want use TTF Font files installed on your system, add to the classpath your fonts directory. iReport comes with an own fonts directory automatically added to the classpath. Started iReport... 1. go to menu->Tools->Options 2. go to tab external programs 3. set external viewers programs

Fig.2.1 : The external programs options tab.

2.3 Final test...


Ok, try if the configuration is ok.... Create a new blank report. Click on the iReport "Run without connection" button After few seconds will appeare our pdf opened with the program that we have set, as signal that all is OK.

3 iReport and JasperReports basic concepts


iReport is not useful without a library called JasperReports. This powerful library is one of the most advanced reporting engine avalaible to the OpenSource community. Before starting to play with iReport, it's important understand what iReport do and why. In this chapter I'll explain some basic concepts on how JasperReports works, what iReport do using "jasper" itself and why it semplify the live of the user.

3.1 How JasperReports works


JasperReport works in a way similar to a compiler and an interprete r. See fig. 3.1. The user design a report coding it in XML in agreement to tags and attributes defined in a file called jasperreports.dtd (part of JasperReports). Using XML a user define the entire report, describing where place texts, images, lines, recta ngles, how to retrive data, how to make certain calculations to show subtotals, etc...

Fig.3.1 : How JasperReports works. This XML source file must be compiled in order to produce a real report. The compiled version of the source is named "jasper file" (it ends with .jasper). A jasper file is a compiled report source. When we have a jasper file, we need another thing in order to produce a report: we need data. This is not always true. In some cases We could want to generate a report that don't shows dynamic data, but i.e. only static text, but this can be reduced to a report that has only an empty record. To supply this records to the jasper engine we need to present it using a special jasperreports specific interface named JRDataSource. A datasource + a jasper file = a print. A print can then be exported in many formats like PDF, HTML, XML, XLS, C VS, etc... The export will be done using special classes the implement specific exporters.

3.2 Compilation end export of reports


For a newbie, design and create the jasper file is the hardest work. When you have designed and compiled your jasper file, you can use the JasperReport library to dinamycally fill your report in several enviroments like a web application (using i.e. java servlet, but I ha ve succesfully used JasperReports for generating PDF reports calling it from a PHP script...). Jasper make available a special viewer to display a report preview, designed for swing based traditional java applications.

Fig.3.2 : JasperReports can easily integrated in a Web application as in a ja va swing based program.

3.3 Our first very simple report


iReport provide to jasperreports users a visual interface to build reports, generate jasper files and test prints. iReport born as development tool, but it can be used as an office tool to retrive and print data stored in a database, without pass through another application.

Fig.3.3 : How JasperReports works. iReport can read and modify both jasper XML and jasper files. Trought jasperreports, it's able to compile XML to jasper files and "run reports" to fill it using several types of JRDataSource and export the result to PDF,HTML,XLS,CSV,... To better understand as all works, we'll do a test. Follow this simple steps: 1. Open iReport and create a new empty document.

Fig.3.4 : New report properties.

2. Add to the title band a static text element

Fig.3.5 : Changing font size....

3. Run the report (iReport will ask for save the file before compile it)

Fig.3.6 : The final report viewed with GhostView.

In this session we have created a simple report, saved as XML file, compiled as jasper file, filled with an "EmptyDataSource" end exported in PDF.

4 Connections and Datasources

Data to print can be retrived in several ways from different places like a database or a XML fil e. This data is presented to JasperReports always in form of records using a special interface called JRDataSource. JasperReports comes with a good set of implementations of this interface to wrap JDBC ResultSets, TableModels, Collections, Vectors and Arrays of objects, etc... But not always a JRDataSource is needed to supply data to the report in order to fill it. In fact JasperReports can execute yourself sql queries using a given opened Connection to a database, and use the result to fill the report. How we'll see, this features will be very useful and easy to use.

4.1 Types of datasource


iReport supports JDBC connections and 4 types of datasource (that can be used to wrap any kind of custom datasource). Empty data source (JREmptyDatasource): is a special datasource used to fill report that don't expose any records. This datasource is used when you press the button to "run" a report. XML DataSource (not yet implemented): is a datasource capable to wrap an XML file and normalize its content. The only informations needed to create this type of datasource are a name (for the datasource) and the name of the XML file.

Fig.4.1 : XML datasource definition.

JavaBeans Set Datasource (not yet implemented): is a datasource capable to wrap a Collection or an Arra y of Ja vaBeans. How all the rest of datasources used by iReport and presented here, this datasource need a spacial factory class that provides a static method to generate a collection or an array of Ja vaBeans (alias a set of Objects). To create this datasource you need a name for the Fig.4.2 : Java Beans Set datasource definition. datasource, the name of a class that will provide the static method to call to retrive the Arra y/Collection of Objects and the name of this method that will have a definition like this:

public static Collection createMyCollection()


or

public static Object[] createMyArray()


Remember to set the type of result (Collection or Array). Custom Datasource: this type of datasource is generic. iReport don't know how the JRDataSource is implemented by this particular connection but it's not important.

Fig.4.3 : Custom J RDatasource definition.

This datasource need a spacial factory class that provides a static method that return a JRDataSource. To create this datasource you need a name for the datasource, the name of a class that will provide the static method to call to retrive the JRDataSource and the name of this method that will have a definition like this:

public static JRDataSource createMyJRDataSource()

An e xample of implementation of a custom datasource is provided at the end of this chapter.

4.2 Setting up a JDBC connection


To set up a JDBC connection we need a running JDBC capable DBMS (I like MySQL), an appropriate JDBC driver to access it, a database and a valid account. Are you ready? Let's go! Select the menu Datasources > Connection/Datasources. Will appeare the frame with the list of datasources and JDBC connections that you have defined. Please note that you can define how many datasources and connecgtions you want but you can, for now, use only one at time. We'll see how set the "Acti ve connection". Press the "New" button. In the new frame, write a connection name (i.e. "My First JDBC connection"), select the right JDBC driver, you can specify one writing it directly or use one already present in the list. Please note that this drivers are not shipped with iReport (except MySQL dri ver), be sure that the driver that you want use is in the classpath. Putting a jar in the lib directory of iReport can be a good idea, but the jars present in this Fig.4.4 : J DBC connection definition frame. directory are added to the CLASSPATH only when iReport start. For now it's not possible change the classpath of iReport 2 dinamically. Before write the URL, write the database name, then press the button "Wizard". In this way, if iReport recognize the driver, it will suggest a URL to use with. Set the username and the password, then test the connection pressing the Test button. If all it's OK, a dialog box (Fig. 4.5) will inform you of the test success. Many software use a very similar way to setting up a JDBC connection. You can refer to the specific JDBC driver documentation to know all options offered by the driver and the exact syntax of the URL. All most used DBMS have a JDBC driver. If you need to access a database via Fig.4.5 : The connection is OK. ODBC on a Win32 system, you can use the JDBC-ODBC brigde, a special JDBC driver developed by Sun Inc.. But I suggest to verify first the presence of a JDBC driver. iReport for default don't store connection passwords. If you want store it, you must first check the "Save password" checkbox. Press the "Save" button to definitly store the connection in the iReport connections pool.

4.3 Setting up a custom datasource


I will not bore to you with other basic slight notions on which butto n you must press in order to execute what is written on it... If you have not, read the previous paragraph that explains where put hands to create a new datasource/connection. You only should to kwnow that you can choose the type of your datasource selecting it by the combobox in the connection frame. When you have filled all fields, test it with the test button.

In this session we have created a simple report, saved as XML file, compiled as jasper file, filled with an "EmptyDataSource" end exported in PDF.

4.4 Implementing a new custom datasource


This topic is more a JasperReports releated argument, than an iReport feature explanation. But I think that can be useful know how you can develope your custom data driver (alias JRDataSource). We will write a very simple JRDataSource that retrive fields from a CSV file. A CSV file is a text file that contains a set row. An y row contains a cartain number of fields separated by a special character (i.e. teh semicolon ';'). What must do our datasource is retrive this rows and return the right value to JasperReport when it ask for a fields (or column). What we have to do is implement this very simple interface:

package dori.jasper.engine; public interface JRDataSource { public boolean next() throws JRException; public Object getFieldValue(JRField jrField) throws JRException; }
A JRField is a vary simple class to. It contains the name of the field (a String), and the java Class that represents the type of this field. In our case all fields are of type String, but we can choose to use as field name (alias the column name) the values of the first row of our cvs file or a generic name as COLUMN_1, COLUMN_2, ... This is the same way used by JasperReport in implementation of the TableModel wrapper datasource, that can indifferently use as column name the value of the column header (if present) or the special name COLUMN_<n> with n in the set {0,1,2,3,...,k}. We'll use fixed names to refer columns in our datasource (COLUMN_1, COLUMN_2, ...). This is the code:

JRCSVDataSource.java
1 2 3 import java.io.*; 4 import java.util.*; 5 6 public class JRCSVDataSource implements dori.jasper.engine.JRDataSource { 7 8 String row = ""; 9 LineNumberReader lineNumberReader; 10 11 /** Creates a new instance of JRCVSDataSource */ 12 public JRCSVDataSource(String cvsFile) { 13 try { 14 lineNumberReader = new LineNumberReader( new FileReader(cvsFile)); 15 } catch (Exception ex) { } 16 } 17 18 public Object getFieldValue(dori.jasper.engine.JRField jRField) throws dori.jasper.engine.JRException { 19 String field = jRField.getName(); 20 int fieldPosition = Integer.parseInt(field.substring(7)); // Strip COLUMN_ 21 StringTokenizer st = new StringTokenizer(row,";"); 22 while (st.hasMoreTokens()) 23 { 24 fieldPosition--; // The column is not 0 indexed. 25 String token = st.nextToken(); 26 if (fieldPosition == 0) return token;

27 28 29 30 31 32 33 34 35 36 37 38

} return null; // Column not found... } public boolean next() throws dori.jasper.engine.JRException { try { row = lineNumberReader.readLine(); if (row.length()>0) return true; } catch (Exception ex) { } return false; } }

How you can see, only 38 lines of code... It's time to test it... We'll write a little "JRDataSourcFactory" in order to use it with iReport. This factory will instance a JRCSVDataSource and will return it with the static method: getTheDatasource()

CSVDatasourceTestFactory.java
1 2 3 4 5 6 7 8 9 10 package it.businesslogic.ireport.connection; public class CSVDatasourceTestFactory { public dori.jasper.engine.JRDataSource getTheDatasource( ) { return new JRCSVDataSource("test.csv"); } }

Open iReport, create a new custom JRDataSource connection and fill all fields as in Fig. 4.6, test and save the connection.

Fig.4.6 : The new CSV datasource connection. Now go to Build > Set active connection and select our new connection ("CSV Datasource (test.csv)")

Fig.4.7 : Set the active connection. This is the result. We'll soon learn how to create the trial report used to test our datasource.

Fig.4.8 : The result print.

5 Bands and groups


In this chapter we'll see how a report is structured and how modify this structure.

5.1 Bands
A report is composed by a variable set of sections named bands. Every band is defined by an height (that should be considered as a minimal height). If the band height is zero, the band will be never visible. The band height can grown if elements inside it are stretched. A minimal document has ever:

Title band Page header Column header Detail Column footer

Title band Page header Column header Detail Column footer Page footer

is printed only one time and it's the first band. It can be printed on a separate page. is printed on each page. is printed on each page that contains a detail band. If a page is split in one or more columns, this band is printed on each column. is printed for each record in the source is printed on each page that contains a detail band. If a page is split in one or more columns, this band is printed on each column. is printed on each page. This is a good place where put something like "Page

Page footer Summary Summary

X of Y" is printed only one time at the end of the report. It can be printed on a separate page.

There is then a special band named background that can be used to define a page background (i.e. using a watermark image). The position of a band respect other bands can not be modifyed. For each band you can modify the minimum height, the value of a flag that allows to split a band during filling process if it's bigger than the portion of page in wich it should be printed, and an boolean expression (alias a java expression that return a Boolean object), with wich is possible control if the band is visible or note. If no expression is defined for a band, the visibility is set to "true".

Fig.5.1 : Bands button on toolbar. Pressing the bands button (see fig.5.1) or selecting the menu item View > Bands , the bands form will be opened.

Fig.5.2 : Bands form. From here it's possible modify the band height and set the band expression. The title and summary bands can be printed on a new page. To use this feature, you must go in the report properties form, select the tab "more" and use the proper checkbox.

Fig.5.3 : Report properties, tab more (menu item View > Report properties).

5.2 Groups
If you need to group data, you can add one or more groups. When a group is created, two new bands are added to the report: the group header and the group footer. Title band Page header Column header Group 1 header Group 2 header Detail Group 2 footer Group 1 footer Column footer Page footer Summary

A group is defined by an expression. For each record processed, JasperReports evaluate this expression. If the expression value is changed, the group change. Please note that JasperReports don't perform any order on data, so if you use a field as expression and values for this fields are A B A B, four groups are created, against the expected two (one for each record with the field value set to A, and one for the records number 2 and 3, with the field value set to B). If you present to JasperReports the ordered data (A A B B), all will works fine.

Fig.5.4 : Gr oups button on toolbar. Pressing the groups button (or selecting the menu item View > Groups) you can open the groups form from wich you can handle groups.

Fig.5.5 : Gr oup definition form. From this form you can set all group properties.

6 iReport plugins
From version 0.3.1, iReport supports a plugin system to extend his features. In this chapter we'll learn how to create an iReport plugin and how to deploy it. An iReport plugin is composed by a descriptor file (an XML document placed in the "plugin" directory) and a set of classes (or a jar) placed in the classpath. Normally, when plugin is loaded, iReport creates an item in the plugin menu on main frame. Plugins are loaded only on iReport startup. When the plugin menu item is selected, iReport instance the plugin (if not yet instanced) and call the plagin's call() method. A plugin is instanced only one time, and in descriptor file it's possible specify to instance it at iReport startup instead to wait for the first user invokation. This is useful when the plugin is marked as "hidden", and it is not visible on the plugin menu.

Fig.6.1 : The plugin menu on iReport main frame. A plugin can be marked as configurable. In this case, the plugin must implement the method configure() that will be executed when the user ask to configure the plugin.

6.1 The abstract iReport plugin


All iReport plugins extends the abstract class it.businesslogic.ireport.plugin.IReportPlugin . This class is really simple:

IReportPlugin.java
1 2 3 4 5 6 7 8 /* * IReportPlugin.java * * Created on 19 maggio 2004, 7.23 */ package it.businesslogic.ireport.plugin;

9 import it.businesslogic.ireport.gui.MainFrame; 10 /** 11 * This class must be extended by all iReport plugin. 12 * To install a plugin into iReport, put the plugin xml in the plugin directory of iReport. 13 * See plugin documentation on how to create a plugin for iReport 14 * 15 * This is the first very simple interface to plugin. I hope to don't change it, but we can't say 16 * what it'll happen in he future... 17 * 18 * @author Administrator 19 */ 20 public abstract class IReportPlugin { 21 22 MainFrame mainFrame = null; 23 String name = ""; 24 25 26 27 /** 28 * This method is called when the plugin is selected from the plugin menu 29 */ 30 public abstract void call(); 31 32 /** 33 * This method is called when the plugin configuration button on plugin list is selected. 34 * Configuration file of plugin should be stored in IREPORT_USER_HOME_DIR/plugins/ 35 */ 36 public void configure(){} 37 38 /** 39 * Retrive the plugin name. Please note that the plugin name must be unique and should be used as 40 * filename for the configuration file if needed. This name can be different from the name specified 41 * in XML, that is the name used for the menu item. 42 */ 43 public String getName(){ 44 return name; 45 } 46 47 /** Getter for property mainFrame. 48 * @return Value of property mainFrame. 49 * 50 */ 51 public it.businesslogic.ireport.gui.MainFrame getMainFrame() { 52 return mainFrame; 53 } 54 55 /** Setter for property mainFrame. 56 * @param mainFrame New value of property mainFrame. 57 * 58 */

59 public void setMainFrame(it.businesslogic.ireport.gui.MainFrame mainFrame) { 60 this.mainFrame = mainFrame; 61 } 62 63 } 64 Please note that the ONLY abstract method that must be implemented is call() that is called each time the plugin
is invoked from the user. If you want add a configuration GUI for you plugin, then you must implement the configure() method too.

6.2 The plugin file descriptor


The plugin file descriptor is a file with an arbitrary name that describe a plugin. The main informations about the plugin are: NAME this is the name that will be displayed in the menu item); CLASS the plugin class that extendes IReportPlugin; ICON FILE an icon used on menu (must be 16x16);

<?xml version="1.0" encoding="UTF-8"?> <!-Document : iReportPlugin.dtd Created on : 19 maggio 2004, 8.09 Author : Giulio Toffoli Description: This DTD define the XML descriptor for an iReport plugin. --> <!-iReportPlugin is the root element. ATTRIBUTES: name The name of plugin class The class that extends it.businesslogic.ireport.plugin.IReportPlugin loadOnStartup If true, the plugin will be instanced on iReport startup hide If true, this plugin will be not visible on plugin menu --> <!ELEMENT iReportPlugin (Author?,Description?, IconFile?)> <!ATTLIST iReportPlugin name NMTOKEN #REQUIRED class NMTOKEN #REQUIRED loadOnStartup (true | false) "false" hide (true | false) "false" congigurable (true | false) "false"> <!ELEMENT Author (#PCDATA)> <!ELEMENT Description (#PCDATA)> <!-Icon file should be a file in the classpath i.e. com/my/plug/in/icon.gif Is used as optional icon for menu. Dim: 16x16

--> <!ELEMENT IconFile (#PCDATA)>

6.3 The hello world plugin


The following example show a really simple plugin that show a simple message when invoked or configured.

HelloWorld.java
1 /* 2 * HelloWorld.java 3 * 4 * Created on 21 maggio 2004, 7.36 5 */ 6 7 package it.businesslogic.ireport.plugin.examples; 8 9 /** 10 * 11 * @author Administrator 12 */ 13 public class HelloWorld extends it.businesslogic.ireport.plugin.IReportPlugin { 14 15 /** Creates a new instance of HelloWorld */ 16 public HelloWorld() { 17 } 18 19 public void call() { 20 javax.swing.JOptionPane.showMessageDialog(this.getMainFrame(), "Hello from plugin!"); 21 } 22 23 public void configure() { 24 javax.swing.JOptionPane.showMessageDialog(this.getMainFrame(), "Hello from plugin configuration!"); 25 } 26 27 } 28

helloworld_descriptor.xml
<iReportPlugin name="Example 1" class="it.businesslogic.ireport.plugin.examples.HelloWorld" loadOnStartup="false" hide = "false" configurable = "true"> <IconFile>/it/businesslogic/ireport/icons/menu/new.gif</IconFile> <Description>This example shows how to create a very simple plugin for iReport.</Description> </iReportPlugin>

7 Using the XML datasource


Starting from version 0.3.2, iReport provides an XML datasource that permit to fill a report reading data from an XML file.

iReport 0.4.0 use JRXmlDatasource shipped with JasperReports (from version 0.6.x)
This new implementation was developed by Peter Severin (developer of JasperAssistant). This new implementation is much powerful supporting real XPath expressions. Here is what JasperReports documentation says about JRXmlDatasource.

net.sf.jasperreports.engine.dat a
Class JRXmlDataSource

java.lang.Object | +--net.sf.jasperreports.engine.data.JRXmlDataSource
All Implemented Interfaces: JRDataSource, JRRewindableDataSource public class JRXmlDataSource extends java.lang.Object implements JRRewindableDataSource XML data source implementation that allows to access the data from a xml document using XPath expressions. The data source is constructed around a node set (record set) selected by an XPath e xpression from the xml document. Each field can provide an additional XPath expresion that will be used to select its value. This expression must be specified using the "fieldDescription" element of the field. The expression is evaluated in the context of the current node thus the expression should be relative to the current node. To support subreports, sub data sources can be created. There are two different methods for cre ating sub data sources. The first one allows to create a sub data source rooted at the current node. The current node can be seen as a new document around which the sub data source is created. The second method allows to create a sub data source that is rooted at the same document that is used by the data source but uses a different XPath select expression. Example:

<A> <B id="0"> <C> <C> </B> <B id="1"> <C> <C> </B> <D id="3"> <E> <E>

</D> </A>

Data source creation new JRXmlDataSource(document, "/A/B") - creates a data source with two nodes of type /A/B new JRXmlDataSource(document, "/A/D") - creates a data source with two nodes of type /A/D Field selection @id - will select the "id" attribute from the current node C - will select the value of the first node of type C under the current node. Sub data source creation "((net.sf.jasperreports.engine.data.JRXmlDataSource)$P{REPORT_DATA_SOURCE}).subDataSource("/B/ C") - in the context of the node B, creates a data source with elements of type /B/C "((net.sf.jasperreports.engine.data.JRXmlDataSource)$P{REPORT_DATA_SOURCE}).dataSource("/A/D") creates a data source with elements of type /A/D Generally the full power of XPath e xpression is available. As an example, "/A/B[@id > 0"] will select all the nodes of type /A/B having the id greater than 0. For a short XPath tutorial check the following URL: Author: Peter Severin (peter_p_s@sourceforge.net, contact@jasperassistant.com) This chapter cover the old iReport implementation of XML datasource. This can help to use the new one.

7.1 Configuring an XML datasource


The first step to use an XML file as a datasource is configure an XML Datasource. Select menu Datasource > Connections / Datasources, press New and select "XML file datasource" as connection type.

Fig.7.1 : The XML datasource configuration pane l. Fill the name field with the name of this datasource (i.e. Adressbook), select the XML file and set the record path.

7.2 The Record Path

An XML document is structured as a tree. JasperReports need data organized as a record set, so we must present a tree as set of record. The Record Path is a string that define the minimum path required to define a record. Example 1:

<palette> <color>Red</color> <color>Green</color> <color>Blue</color> </palette>


It this very simple case, the Record Path is the path from the root (tag palette) to the leaf (tag color): /palette/color We use the same record path for this document (Example 2):

<palette> <color> <name>Red</name> <red>255<red> <green>0<green> <blue>0<blue> </color> <color> <name>Green</name> <red>0<red> <green>255<green> <blue>0<blue> </color> <color> <name>Blue</name> <red>255<red> <green>0<green> <blue>0<blue> </color> </palette>
Please note that in this case the path don't ends with a leaf tag. In general, the end tag is the first tag that has children of different type or is a leaf. When the document become more complex, we can read prodoce a sub-datasource starting from a child. In example 3 we can see that any color can have 0 or more aliases...

<palette> <color> <name>Red</name> <alias type="html">#FF0000</alias> <alias type="rgb">255, 0, 0</alias> <alias type="CMYK">0, 99, 100, 0</alias> </color> <color> <name>Green</name> <alias type="html">#0000FF</alias> <alias type="rgb">0, 0, 255</alias> <alias type="lab">88, -79, 81</alias> <alias type="CMYK">63, 0, 100, 0</alias> </color> <color> <name>Blue</name> <alias type="html">#0000FF</alias> <alias type="rgb">0, 0, 255</alias> </color> </palette>
In this case we can think to tags alias as a set of records childs of master record /palette/color, the childs record will have as record path the value /color/alias:

<color>

<alias type="html">#FF0000</alias> <alias type="rgb">255, 0, 0</alias> <alias type="CMYK">0, 99, 100, 0</alias> </color>
Note as this XML is very similar to example 1.

7.3 XML Datasource Syntax


To bind fields inside the XML, a synta x similar to XPath is used. The field path is stored in the field description (this because the field name don't support a name like "/palette/color"). The path syntax is really simple. Is a recursive expression:

<base_path>[<symbol> <base_path>[<symbol><...>] ]
<base_path> is the path from the root to the tag. If this path is longer than the Record Path, it's cuted to the Record Path. It is required for a field definition. If it's alone, the value of the tag is returned. Example: /palette/color <symbol> is used to add an extra path to the base path and to define what should be returned. + add the following path to the base_path (this happen when the base_path = record path); @ return the attribute value: it's followed by the attribute name; * return all tags identified by the following path as a JRXMLDatasource Examples: /palette/color+name /color/alias@type /palette/color*alias /addressbook/catogory/person+other_info+extra_time/hobbies*hobby /addressbook@creation_date

7.4 Addressbook sample


This sample shows how to use the JRXMLDatasource using subreports. The sample is composed by 4 files: addressbook.xml is the data file addressbook.jrxml is the master report file hobby.jrxml is the hobby subreport eamil.jrxml is the email subreport

addressbook.xml
<addressbook> <category name="home"> <person id="1"> <LASTNAME>Davolio</LASTNAME> <FIRSTNAME>Nancy</FIRSTNAME> <hobbies> <hobby>Radio Control</hobby> <hobby>R/C Cars</hobby> <hobby>Micro R/C Cars</hobby> <hobby>Die-Cast Models</hobby> </hobbies> <email>email1@my.domain.it</email> <email>email2@my.domain2.it</email>

</person> <person id="2"> <LASTNAME>Fuller</LASTNAME> <FIRSTNAME>Andrew</FIRSTNAME> <email>email3@my.domain3.it</email> <email>email4@my.domain4.it</email> </person> <person id="3"> <LASTNAME>Leverling</LASTNAME> <FIRSTNAME>Janet</FIRSTNAME> <hobbies> <hobby>Rockets</hobby> <hobby>Puzzles</hobby> <hobby>Science Hobby</hobby> <hobby>Toy Horse</hobby> </hobbies> <email>email45@my.domain3.it</email> <email>email455@my.domain4.it</email> </person> </category> <category name="work"> <person id="4"> <LASTNAME>Peacock</LASTNAME> <FIRSTNAME>Margaret</FIRSTNAME> <hobbies> <hobby>Toy Horse</hobby> </hobbies> <email>Peacock@margaret.com</email> </person> <person id="5"> <LASTNAME>Buchanan</LASTNAME> <FIRSTNAME>Steven</FIRSTNAME> <hobbies> </hobbies> <email>Buchanan@steven.com</email> </person> <person id="6"> <LASTNAME>Suyama</LASTNAME> <FIRSTNAME>Michael</FIRSTNAME> </person> <person id="7"> <LASTNAME>King</LASTNAME> <FIRSTNAME>Robert</FIRSTNAME> </person> </category> <category name="Other"> <person id="8"> <LASTNAME>Callahan</LASTNAME> <FIRSTNAME>Laura</FIRSTNAME> <email>email25@my.domain3.it</email> </person> <person id="9"> <LASTNAME>Dodsworth</LASTNAME> <email>Dodsworth@my.anne.it</email> </person> </category> </addressbook>

We have defined a datasource named Addressbook that use addressbook.xml as data file. The Record path is: /addressbook/category/person Fields in the report are defined as follow: Field Name CATEGOR Y PERSON_ID LASTN AME FIRSTN AME Type java.lang.String java.lang.String java.lang.String java.lang.String HOBBIES /addressbook/category/person+hobbies*hobby java.lang.Object (castable to JRDataSource) java.lang.Object (castable to EMAIL_ADDRESSES /addressbook/category/person*email JRDataSource) To the master report (figure 7.2) we have added a group named CATEGOR Y that has as expression the category name. Field Description /addressbook/category@name /addressbook/category/person@id /addressbook/category/person+LASTNAME /addressbook/category/person+FIRSTNAME

Fig.7.2 : The master report. We have two subreport too, one for hobbies of a person and one for email addresses. The first subreport element has $F{HOBBIES} as connection expression (of type datasource expression) and as subreport expression "/hobby.jasper" of type String. The second subreport element has $F{EMAIL_ ADDRESSES} as connection expression (of type datasource expression) and as subreport expression "/email.jasper" of type String. In hobby.jasper we have defined only one field: Field Name Field Description Type HOBBY /hobbies/hobby java.lang.String The same in email.jasper: Field Name Field Description Type EMAIL /person/email java.lang.String Note as every field in subreport are defined specifing as root element in the path the parent element: HOBBY -> /hobbies/hobby EMAIL -> /person/email This is the result:

Fig.7.2 : The final result. Finally we show how to use the JRXMLDataDource in a program:

XMLDataSourceExample.java
1 package it.businesslogic.ireport.examples; 2 3 import it.businesslogic.ireport.connection.JRXMLDataSource; 4 import dori.jasper.engine.export.JRPdfExporter; 5 6 import dori.jasper.engine.*; 7 import java.util.HashMap; 8 9 10 public class XMLDataSourceExample { 11 12 public static void main(String[] args) throws Exception { 13 14 String reportFileName = "/addressbook.jasper"; 15 String outFileName = "/addressbook.pdf"; 16 String xmlFileName = "/addressbook.xml"; 17 String recordPath = "/addressbook/category/person"; 18 19 JRXMLDataSource jrxmlds = new JRXMLDataSource(xmlFileName,recordPath); 20 21 HashMap hm = new HashMap();

22 23 try 24 { 25 JasperPrint print = JasperFillManager.fillReport( 26 reportFileName, 27 hm, 28 jrxmlds); 29 30 JRExporter exporter = new dori.jasper.engine.export.JRPdfExporter(); 31 32 exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,outFileName); 33 exporter.setParameter(JRExporterParameter.JASPER_PRINT,print); 34 35 exporter.exportReport(); 36 System.out.println("Created file: " + outFileName); 37 } 38 catch (JRException e) 39 { 40 e.printStackTrace(); 41 System.exit(1); 42 } 43 catch (Exception e) 44 { 45 e.printStackTrace(); 46 System.exit(1); 47 } 48 49 } 50 51 }

7.5 XML Datasource license


JRXMLDatasource is not released under GPL license (as iReport is) but under LGPL as jasperreports: in this way you can use the JRXMLDataSource in your program without problems. However, if you use it, please make a simbolic donation to the iReport project.

8 Charts
JasperReports does not manage directly charts: they must be created independently as images, even using one of numerous open-source java libraries availables to create charts. The produced image will be shown using an image element. The idea is really simple, but the creation of a chart at run time requires a good knowledge of JasperReports programming, and many times it's needed to use write scriptlets capable of collecting data that willl be exposed by the chart. With version 0.4.0, iReport provides a solution to semplify chart building with a new chart tool. This tool permits to create a chart configuring main properties and data to feed it in a very simple manner for the final user. Creation of a chart is delagated to a well know open source library named JFreeCharts (version 0.9.21) developed by David Gilbert from Object Refinery Limited. iReport supportas for now only a little number of chart types exposed from JFreeCharts, and can be modified only few chart properties (in effect JFreeChart permits a really fine control on all chart properties), but it's possible, anyway, create clear chart with a big vision impact.

8.1 Creation of a simple chart


In this paragraph we'll take confidence with chart tool, building a report with a Pie3D chart step by step; subsequently we'll take a look on all details related to the chart handling. In the sample we'll use as Datasource the NorthWind database on HSQLDB. We start opening a blank document. Open the query window using this button: this query: and write in the SQL textfield

select SHIPCOUNTRY, COUNT(*) AS ORDERS_COUNT from ORDERS group by SHIPCOUNTRY

Fig. 8.1 The report query

The idea is create a chart to illustrate sales in different states. Executed the quey, seleced fields will appeare on the list. Confirm the field registration pressing the OK button: all field retrived from the query will be registered to the report. We can position fields in the report detail dragging it, i.e. from the objects library (fig. 8.1).

Fig. 8.2 The report with field HIPCOUNTRY. We have to set the height of no useful bands (all excluse summary and details) to zero. Select the chart tool and draw a rectangle in the summary band with mouse.

Fig. 8.3 We put the chart in the summary band. iReport will alert about need to activate the internal scriptlet support to handle scriptlet: click YES. From the chart palette select i.e.the Pie3D chart type and press OK. We should be now in the situation showed in figure 8.2. At this point we must configure the chart. Open element properties window (double click on element), go to chart tab and press "Edit chart properties".

Fig. 8.4 Chart Tab. Will appears the chart properties window (the same from wich we are choose the chart type, fig.8.5 ).

Fig. 8.5 Chart type Tab This window is organized with three tabs: e: Chart type, Data and Chart details. The first tab permits to choose the chart type to show: every chart need data structured in series; all series needed by the selected chart type are listed in the frame labeled "Chart Info" on tab bottom where is exposed the name of the chart type and the library used to generate it (for now all charts are produced using JFreeChart 0.9.21, but iReport can support other libraries). In our case we'll need a serie to store labels (exposed in the Y axis), and a single serie of nambers (named Serie 1). Mo ve us on Data tab. We'll find a table with two rows ready to get the name the two series that satisfy the chart needs (fig. 8.6).

Fig. 8.6 Tab Data. They are different ways to create a serie. For now we'll use the simplest way: we'll leave iReport handle the serie for us. Select the "Report series" button to open the report series window (fig. 8.5).

Fig. 8.7 Report series. Create a brand new serie pressing "New serie". The window in fig. 8.8 will appear. Give a name for the serie (i.e. COUNTRY) and set the "Reset When" to . Now we have to write an expression for the value that we want collect to generate the serie. In our case we'll have a serie of strings for SHIPCOUNTRY and a serie of integer numbers for Serie1.

Fig 8.8 Serie definition. To use the expression editor, press the left mouse button over the text area and select the "Use texteditor" menu item. Add all the two series , go back to window of fig. 8.6 and select the two created series from the two comboboxes to assign on Labels the SERIE_COUNTRY and on Serie1 the SERIE_ORDERS_COUNT. Confirm chart properties modifications, save file and run the report using teh active datasource (button on the toolbar). You can show the final result on fig 8.9.

Fig 8.9 The final report with the chart.

On iReport Guide: Series: Automatic Series, Custom series Chart Types: Pie Chart, Pie3D Chart, Bar, Bar3D, Line, Area

Вам также может понравиться