Академический Документы
Профессиональный Документы
Культура Документы
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
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
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
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
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.
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.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.
Fig.3.2 : JasperReports can easily integrated in a Web application as in a ja va swing based program.
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.
3. Run the report (iReport will ask for save the file before compile it)
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.
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.
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:
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:
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.
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.
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 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
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.
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.
<?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
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>
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.
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.
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> <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.
<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
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 }
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.
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.
On iReport Guide: Series: Automatic Series, Custom series Chart Types: Pie Chart, Pie3D Chart, Bar, Bar3D, Line, Area