JasperReports – Crosstabs ”; Previous Next Crosstab (cross-tabulation) reports are the reports containing tables that arrange data across rows and columns in a tabular form. Crosstab object is used for inserting a crosstab report within the main report. Crosstabs can be used with any level of data (nominal, ordinal, interval, or ratio), and usually display the summarized data, contained in the report variables, in the form of a dynamic table. Variables are used to display aggregate data such as sums, counts, average values. Crosstab Properties JRXML element <crosstab> is used to insert a crosstab into a report. Attribute Following is a list of attribute of a <crosstab> element − isRepeatColumnHeaders − Indicates whether the column headers should be reprinted after a page break. The default value is true. isRepeatRowHeaders − Indicates whether the row headers should be reprinted after a crosstab column break. The default value is true. columnBreakOffset − When a column break occurs, indicates the amount of vertical space, measured in pixels, before the subsequent crosstab piece to be placed below the previous one on the same page. The default value is 10. runDirection − Indicates whether the crosstab data should be filled from left to right (LTR) or from right to left (RTL). The default value is LTR. ignoreWidth − Indicates whether the crosstab will stretch beyond the initial crosstab width limit and don”t generate column breaks. Else it will stop rendering columns within the crosstab width limit and continue with the remaining columns only after all rows have started rendering. The default value is false. Sub Elements A <crosstab> element has following sub elements − <reportElement> − This element defines the position, width, and height of the crosstab within its enclosing. Attributes for this element include all standard <reportElement> attributes. <crosstabParameter> − This element is used to access report variables and parameters from within the crosstab. Attributes for this element include − name − This defines the parameter name. class − This indicates the parameter class. <parametersMapExpression> − This element is used to pass a report variable or parameter containing an instance of java.util.Map, as a set of parameters for the crosstab. This element contains no attributes. <crosstabDataset> − This element defines the dataset to use to populate the crosstab (see next section for a detailed explanation). Attributes for this element include − isDataPreSorted − This indicates whether the data in the dataset is pre-sorted. Default value is false. <crosstabHeaderCell> − This element defines the content of the region found at the upper-left corner of the crosstab where column headers and row headers meet. The size of this cell is calculated automatically based on the defined row and column widths and heights. <rowGroup> − This element defines a group used to split the data into rows. Attributes for this element include − name − This defines the name of the row group. width − This defines the width of the row group. headerPosition − This defines the position of the header contents (Top, Middle, Bottom, Stretch). totalPosition − This defines the position of the entire column (Start, End, None). This element contains the following sub elements − <bucket> <crosstabRowHeader> <crosstabTotalRowHeader> <columnGroup> − This element defines a group used to split the data into columns. Attributes for this element include − name − This defines the column group name. height − This defines the height of the column group header. headerPosition − This defines the position of the header contents (Right, Left, Center, Stretch). totalPosition − This defines the position of the entire column (Start, End, None). This element contains the following sub elements − <bucket> <crosstabColumnHeader> <crosstabTotalColumnHeader> <measure> − This element defines the calculation to be performed across rows and columns. Attributes for this element include − name − This defines the measure name. class − This indicates the measure class. calculation − This indicates the calculation to be performed between crosstab cell values. Its values could be any of these – Nothing, Count, DistinctCount, Sum, Average, Lowest, Highest, StandardDeviation, Variance, and First. Default value is Nothing. <crosstabCell> − This element defines how data in non-header cells will be laid out. Attributes for this element include − columnTotalGroup − This indicates the group to use to calculate the column total. height − This defines the height of the cell. rowTotalGroup − This indicates the group to use to calculate the row total. width − This defines the width of the cell. <whenNoDataCell> − This element defines what to display on an empty crosstab cell. This element contains no attributes. Data Grouping in Crosstab The crosstab calculation engine aggregates data by iterating through the associated dataset records. In order to aggregate data, one needs to group them first. In a crosstab, rows and columns are based on specific group items, called buckets. A bucket definition should contain − bucketExpression − The expression to be evaluated in order to obtain data group items. comparatorExpression − Needed in the case the natural ordering of the values is not the best choice. orderByExpression − Indicates the value used to sort data. Row and column groups (defined above) in a crosstab rely on buckets. Built-In Crosstab Total Variables Below is a list of current value of measure and totals of different levels corresponding to the cell can be accessed through variables named according to the following scheme − The current value of a measure calculation is stored in a variable having the same name as the measure. <Measure>_<Column Group>_ALL − This yields the total for all the entries in the column group from the same row. <Measure>_<Row Group>_ALL − This yields the total for all the entries in the row group from the same column. <Measure>_<Row Group>_<Column Group>_ALL − This yields the combined total corresponding to all the entries in both row and column groups. Example To demonstrate the crosstabs, let”s write a new report template (jasper_report_template.jrxml). Here, we will add the crosstab to summary section. Save it to the directory C:toolsjasperreports-5.0.1test. The contents of the file
Category: jasper Reports
JasperReports – Life Cycle
JasperReports – Life Cycle ”; Previous Next The main purpose of JasperReports is to create page oriented, ready to print documents in a simple and flexible manner. The following flow chart depicts a typical work flow while creating reports. As shown in the image, the life cycle has following distinct phases − Designing the report − In this step we, create the JRXML file, which is an XML document that contains the definition of the report layout. We can use any text editor or iReportDesigner to manually create it. If iReportDesigner is used, the layout is designed in a visual way, hence real structure of the JRXML can be ignored. Compiling the report − In this step, JRXML is compiled in a binary object called a Jasper file (*.jasper). This compilation is done for performance reasons. Jasper files are what you need to ship with your application in order to run the reports. Executing the report (Filling data into the report) − In this step, data from the application is filled in the compiled report. The class net.sf.jasperreports.engine.JasperFillManager provides necessary functions to fill the data in the reports. A Jasper print file (*.jrprint) is created, which can be used either to print or export the report. Exporting the report to desired format − In this step, we can export the Jasper print file created in the previous step to any format using JasperExportManager. As Jasper provides various forms of exports, hence with the same input, we can create multiple representations of the data. A detailed overview of each of the above steps will be given in the subsequent chapters. Print Page Previous Next Advertisements ”;
JasperReports – Home
JasperReports Tutorial PDF Version Quick Guide Resources Job Search Discussion JasperReports is an open source java reporting engine. JasperReports is a Java class library, and it is meant for those Java developers who need to add reporting capabilities to their applications. This simple and user-friendly tutorial covers almost all the basics of JasperReports that a beginner should know. Audience This tutorial is designed for Software Professionals as well as for all those beginners who would like to learn the concepts of JasperReports. Prerequisites Before proceeding with this tutorial, it is expected that you have a basic understanding of Java programming language. A basic understanding of Java and other associated programming will be an additional advantage to understand the topic. Print Page Previous Next Advertisements ”;
JasperReports – Data Sources
Report Data Sources ”; Previous Next Datasources are structured data container. While generating the report, JasperReports engine obtains data from the datasources. Data can be obtained from the databases, XML files, arrays of objects, and collection of objects. We saw in the chapter Filling Reports, the fillReportXXX () method expects to receive a data source of the report, which has to fill, in the form of net.sf.jasperreports.engine.JRDataSource object or a java.sql.Connection (when the report data is found in a relational database). The JRDataSource interface has only two methods, which should be implemented − public boolean next() throws JRException; At the report filling time, this method is called on the data source object by the reporting engine when iterating through the data. public Object getFieldValue(JRField jrField) throws JRException; This method provides the value for each report field in the current data source record. The only way to retrieve data from the data source is by using the report fields. There are several default implementations of the JRDataSource interface, depending on the way, the records in the data source are acquired. Datasource Implementations The table given below summarizes the datasources and their implementation classes − Datasource Implementation Class JDBC net.sf.jasperreports.engine.JRResultSetDataSource JavaBean net.sf.jasperreports.engine.data.JRBeanCollectionDataSource, net.sf.jasperreports.engine.data.JRBeanArrayDataSource Map-based net.sf.jasperreports.engine.data.JRMapArrayDataSource, net.sf.jasperreports.engine.data.JRMapCollectionDataSource TableModel net.sf.jasperreports.engine.data.JRTableModelDataSource XML net.sf.jasperreports.engine.data.JRXmlDataSource CSV net.sf.jasperreports.engine.data.JRCsvDataSource XLS net.sf.jasperreports.engine.data.JRXlsDataSource Empty net.sf.jasperreports.engine.JREmptyDataSource JDBC Data Sources Class JRResultSetDataSource craps a java.sql.ResultSet object. This is the most commonly used data source implementations when report data are extracted from a relational database. If a java.sql.Connection is passed to the engine instead, it executes first the related query and stores the returned java.sql.ResultSet object in a JRResultSetDataSource instance. JavaBean Data Sources Classes JRBeanArrayDataSource and JRBeanCollectionDataSource represent implementations that can wrap arrays and collections of JavaBean objects. Each object inside the array or the collection will be seen as one record in this type of data source. The mapping between a particular JavaBean property and the corresponding report field is made by naming conventions. The name of the report field must be the same as the name of the JavaBean property as specified by the JavaBeans specifications. In all the examples of this tutorial, we have used JRBeanCollectionDataSource. Map-based Data Sources The implementation classes JRMapArrayDataSource and JRMapCollectionDataSource are useful if the parent application already stores the reporting data available in-memory as java.util.Map objects. Each Map object in the wrapped array or collection is considered a virtual record in the data source, and the value of each report field is extracted from the map using the report field named as the key. TableModel Data Sources In many client-side applications, data is displayed in tabular format. A common requirement in many applications is to allow the user to print this tabular format as a report. Implementation class JRTableModelDataSource makes the task of generating reports from tabular format trivial for Swing applications. This class wraps a javax.swing.table.TableModel object. Columns in the wrapped TableModel object can be accessed either by their names or by their 0-based indexes. XML Data Sources Class JRXmlDataSource is a data source implementation based on DOM, which uses XPath expressions to select data from the XML document. Records in the XML data source are represented by node elements selected through the XPath expression. Field values are retrieved from each record using the XPath expression provided by the field description (<fieldDescription> element in JRXML). XPath is a language used to navigate through an XML document”s attributes and elements. More information about XPath can be found at http://www.w3.org/TR/xpath. CSV Data Sources JRCsvDataSource represents an implementation for data sources, which retrieve their data from structured text files; usually CSVs. Field values are retrieved using their column index. XLS Data Sources JRXlsDataSource represents an implementation for data sources, which retrieve their data from Excel documents. Report-field mapping for this data source implementation is also based on the field column index. Empty Data Sources The class JREmptyDataSource, simulates a data source with a given number of virtual empty records inside. It is used by the UI tools to offer basic report preview functionality, or in special report templates, or for testing and debugging purposes. Rewindable Data Sources The net.sf.jasperreports.engine.JRRewindableDataSource extends the basic JRDataSource interface. It adds only one method, called moveFirst (), to the interface. This method is intended to move the cursor to the first element in the datasource. Rewindable data sources are useful when working with sub-reports placed inside a band that is not allowed to split due to the isSplitAllowed=”false” setting and there is not enough space on the current page for the sub report to be rendered. All the above data source implementations are rewindable except for the JRResultSetDataSource, as it does not support moving the record pointer back. This poses a problem only if this data source is used manually to wrap a java.sql.ResultSet before passing it to the sub-report. There is no problem, if the SQL query resides in the sub-report template, as the engine will execute it again when restarting the sub-report on the next page. Data Source Providers The JasperReports library has an interface net.sf.jasperreports.engine.JRDataSourceProvider. This helps in creating and disposing of data source objects. When creating a report template using GUI tools, a special tool for customizing the report”s data source is needed. JRDataSourceProvider is the standard way to plug custom data sources into a design tool. A custom implementation of this interface should implement the following methods that allow creating and disposing of data source objects and also methods for listing the available report fields inside the data source if possible − public boolean supportsGetFieldsOperation(); public JRField[] getFields(JasperReport report) throws JRException, UnsupportedOperationException; public JRDataSource create(JasperReport report) throws JRException; public void dispose(JRDataSource dataSource) throws JRException; Print Page Previous Next Advertisements ”;
JasperReports – Designs
JasperReports – Designs ”; Previous Next The JRXML templates (or JRXML files) in JasperReport are standard XML files, having an extension of .jrxml. All the JRXML files contain tag <jasperReport>, as root element. This in turn contains many sub-elements (all of these are optional). JasperReport framework can handle different kinds of data sources. In this tutorial, we shall show how to generate a basic report, just by passing a collection of Java data object (using Java beans), to the JasperReport Engine. The final report shall display a list of people with the categories including their names and countries. The Following steps are covered in this chapter to describe — how to design a JasperReport − Creating a JRXML Report Template and. Previewing the XML Report Template. Creating a JRXML Report Template Create the JRXML file, which is jasper_report_template.jrxml using a text editor and save this file in C:toolsjasperreports-5.0.1test as per our environment setup. <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE jasperReport PUBLIC “//JasperReports//DTD Report Design//EN” “http://jasperreports.sourceforge.net/dtds/jasperreport.dtd”> <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 = “jasper_report_template” language = “groovy” pageWidth = “595” pageHeight = “842” columnWidth = “555” leftMargin = “20” rightMargin = “20” topMargin = “20” bottomMargin = “20”> <queryString> <![CDATA[]]> </queryString> <field name = “country” class = “java.lang.String”> <fieldDescription><![CDATA[country]]></fieldDescription> </field> <field name = “name” class = “java.lang.String”> <fieldDescription><![CDATA[name]]></fieldDescription> </field> <columnHeader> <band height = “23”> <staticText> <reportElement mode = “Opaque” x = “0” y = “3” width = “535” height = “15” backcolor = “#70A9A9” /> <box> <bottomPen lineWidth = “1.0” lineColor = “#CCCCCC” /> </box> <textElement /> <text><![CDATA[]]> </text> </staticText> <staticText> <reportElement x = “414” y = “3” width = “121” height = “15” /> <textElement textAlignment = “Center” verticalAlignment = “Middle”> <font isBold = “true” /> </textElement> <text><![CDATA[Country]]></text> </staticText> <staticText> <reportElement x = “0” y = “3” width = “136” height = “15” /> <textElement textAlignment = “Center” verticalAlignment = “Middle”> <font isBold = “true” /> </textElement> <text><![CDATA[Name]]></text> </staticText> </band> </columnHeader> <detail> <band height = “16”> <staticText> <reportElement mode = “Opaque” x = “0” y = “0” width = “535” height = “14” backcolor = “#E5ECF9” /> <box> <bottomPen lineWidth = “0.25” lineColor = “#CCCCCC” /> </box> <textElement /> <text><![CDATA[]]> </text> </staticText> <textField> <reportElement x = “414” y = “0” width = “121” height = “15” /> <textElement textAlignment = “Center” verticalAlignment = “Middle”> <font size = “9” /> </textElement> <textFieldExpression class = “java.lang.String”> <![CDATA[$F{country}]]> </textFieldExpression> </textField> <textField> <reportElement x = “0” y = “0” width = “136” height = “15” /> <textElement textAlignment = “Center” verticalAlignment = “Middle” /> <textFieldExpression class = “java.lang.String”> <![CDATA[$F{name}]]> </textFieldExpression> </textField> </band> </detail> </jasperReport> Here are the details of main fields in the above report template − <queryString> − This is empty (as we are passing data through Java Beans). Usually contains the SQL statement, which retrieves the report result. <field name> − This element is used to map data from data sources or queries, into report templates. name is re-used in the report body and is case-sensitive. <fieldDescription> − This element maps the field name with the appropriate element in the XML file. <staticText> − This defines the static text that does not depend on any datasources, variables, parameters, or report expressions. <textFieldExpression> − This defines the appearance of the result field. $F{country} − This is a variable that contains the value of result, predefined field in the tag <field name>. <band> − Bands contain the data, which is displayed in the report. Once the report design is ready, save it in C: directory. Previewing the XML Report Template There is a utility net.sf.jasperreports.view.JasperDesignViewer available in JasperReports JAR file, which helps in previewing the report design without having to compile or fill it. This utility is a standalone Java application, hence can be executed using ANT. Let”s write an ANT target viewDesignXML to view the JRXML. So, let”s create and save build.xml under C:toolsjasperreports-5.0.1test directory (should be placed in the same directory where JRXML is placed). Here is the build.xml file − <?xml version = “1.0” encoding = “UTF-8”?> <project name = “JasperReportTest” default = “viewDesignXML” basedir = “.”> <import file = “baseBuild.xml” /> <target name = “viewDesignXML” description = “Design viewer is launched to preview the JXML report design.”> <java classname = “net.sf.jasperreports.view.JasperDesignViewer” fork = “true”> <arg value = “-XML” /> <arg value = “-F${file.name}.jrxml” /> <classpath refid = “classpath” /> </java> </target> </project> Next, let”s open a command prompt and go to the directory where build.xml is placed. Execute the command ant (As the viewDesignXML is the default target). Output is follows − C:toolsjasperreports-5.0.1test>ant Buildfile: C:toolsjasperreports-5.0.1testbuild.xml viewDesignXML: [java] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory). [java] log4j:WARN Please initialize the log4j system properly. Log4j warning can be ignored, and as a result of above execution, a window labeled “JasperDesignViewer” opens, displaying our report template preview. As we see, only report expressions for obtaining the data are displayed, as JasperDesignViewer doesn”t have access to the actual data source or report parameters. Terminate the JasperDesignViewer by closing the window or by hitting Ctrl-c in the command-line window. Print Page Previous Next Advertisements ”;
JasperReports – Environment Setup ”; Previous Next JasperReports is a pure Java library and not a standalone application. It cannot run on its own, hence it needs to be embedded into another client or server-side Java application. As it is Java based, it can be run on any platform that supports Java (JDK 1.3 and above). All the JasperReport”s functionalities are gathered in a single JAR file, jasperreports-x.x.x.jar. This JAR along with the required and optional libraries (.ZIP file) can be downloaded from the site: JasperReport Library Link. Download the latest version from this link. The ZIP file includes the JasperReports JAR file along with the JasperReports source code, dependent JARs, and a lot of examples demonstrating JasperReport”s functionalities. JasperReport Environment To start creating the reports, we need to set up the environment ready. Extract the downloaded JasperReport.ZIP file to any location (in our case, we have extracted it to C:toolsjasperreports-5.0.1). The directory structure of the extracted file is same as shown below − Here is the detail of all the directories − build − Contains the compiled JasperReport class files. demo − Contains various examples, demonstrating several aspects of JasperReports functionality. dist − Contains jasperreports-x.x.x.jar file. We shall add this JAR file to our CLASSPATH to take advantage of JasperReports. docs − Contains a local copy of the JasperReports documentation. lib − Contains all JARs needed, both to build JasperReports and to use it in our applications. src − Contains the JasperReports source code. build.xml − An ANT build file to build the JasperReports source code. If we don”t intend to modify JasperReports, we don”t need to use this file since JasperReports is distributed in the compiled form. changes.txt − A text document, explaining the differences between the current and previous versions of the JasperReports class library. license.txt − A text document that contains the full text of the LGPL (Lesser General Public License) license. readme.txt − A text document, containing instructions on how to build and execute the supplied examples. Basically, we only use the jasperreports-x.x.x.jar under the dist and JARs under the lib directory for generating reports. As JasperReports being an open source tool, if any defect or bug is recognized during execution in the jasperreports-x.x.x.jar, we can fix it and build the JAR again using the build.xml file. Set the CLASSPATH To use JasperReport, we need to set the following files to our CLASSPATH − jasperreports-x.x.x.jar, where x.x.x is the JasperReports version. This found under directory C:toolsjasperreports-x.x.xdist). All the JAR files under the lib subdirectory (C:toolsjasperreports-x.x.xlib). At the time of installation, we used JasperReport version 5.0.1. Right-click on ”My Computer” and select ”Properties”, click on the ”Environment variables” button under the ”Advanced” tab. Now update the ”Path” variable with this C:toolsjasperreports-5.0.1distjasperreports-5.0.1.jar:C:toolsjasperreports-5.0.1lib. Now you are ready to create your reports. In all the examples in this tutorial, we have used ANT tasks to generate reports. The build file takes care of importing all the required JARs for generating reports. Hence, setting CLASSPATH as mentioned above will only help those who wish to generate reports without using ANT. Build Setup All the examples in this tutorial − have been written using simple Text Editor. have been saved under the directory C:toolsjasperreports-5.0.1testsrccomtutorialspoint. have been compiled and executed from command prompt, using Apache ANT. We will use a baseBuild.xml file, which we shall import in ANT build.xml file in the subsequent chapters. Save this file to C:toolsjasperreports-5.0.1test. Following is the content of baseBuild.xml file − <?xml version = “1.0” encoding = “UTF-8”?> <project name = “JasperReportExample” basedir = “.”> <description>Previews our JasperReport XML Design</description> <property name = “file.name” value = “jasper_report_template” /> <!– Directory where the JasperReports project file was extracted needs to be changed to match the local environment –> <property name = “jasper.dir” value = “../” /> <property name = “dist.dir” value = “${jasper.dir}/dist” /> <property name = “lib.dir” value = “${jasper.dir}/lib” /> <property name = “src.dir” value = “src” /> <property name = “classes.dir” value = “classes” /> <property name = “main-class” value = “com.tutorialspoint.HelpMe” /> <path id = “classpath”> <pathelement location = “./” /> <pathelement location = “${classes.dir}” /> <fileset dir = “${lib.dir}”> <include name = “**/*.jar” /> </fileset> <fileset dir = “${dist.dir}”> <include name = “**/*.jar” /> </fileset> </path> <target name = “compile” depends = “clean-sample”> <mkdir dir = “${classes.dir}”/> <javac srcdir = “${src.dir}” destdir = “${classes.dir}” classpathref = “classpath” /> </target> <target name = “run” depends = “compile”> <echo message = “Running class : ${main-class}”/> <java fork = “true” classname = “${main-class}”> <classpath> <path refid = “classpath” /> </classpath> </java> </target> <target name = “clean-sample”> <delete dir = “${classes.dir}” /> <delete file = “./${file.name}.jasper” /> <delete file = “./${file.name}.jrprint” /> </target> </project> This file has all the required targets, like cleaning the directories, compiling the java files, and executing the class files. Following are the details, mentioned by various directories in baseBuild.xml. Assuming current directory is C:toolsjasperreports-5.0.1test) − jasper.dir − is C:toolsjasperreports-5.0.1 directory lib.dir − is C:toolsjasperreports-5.0.1lib directory src.dir − is C:toolsjasperreports-5.0.1testsrc classes.dir − is C:toolsjasperreports-5.0.1testclasses main-class − com.tutorialspoint.HelpMe. This class is a simple class executed, when no class file name is passed from the command line. Save this file to C:toolsjasperreports-5.0.1testsrccomtutorialspoint. package com.tutorialspoint; public class HelpMe { public static void main(String[] args) { System.out.println(“This is the default class executed.” + “Please pass the fully qualified class” + ” name to be executed as command line” + ” parameter, for example,” + ” com.tutorialspoint.HelpMe “); } } Jasper Managers Classes There are number of classes, which will be used to compile a JRXML report design, to fill a report, to print a report, to export to PDF, HTML & XML files, view the generated reports, and report design. The list of these classes is − net.sf.jasperreports.engine.JasperCompileManager − Used to compile a JRXML report template. net.sf.jasperreports.engine.JasperFillManager − Used to fill a report with data from the data source. net.sf.jasperreports.engine.JasperPrintManager − Used to print the documents generated by the JasperReports library. net.sf.jasperreports.engine.JasperExportManager − Used to obtain PDF, HTML, or XML content for
JasperReports – Sections
Report Sections ”; Previous Next We discussed the structure of a simple report template in the chapter Getting Started. On similar lines, JasperReports structures the report template into multiple sections. Sections are portions of the report that have a specified height and can contain report objects like lines, rectangles, images, or text fields. The report engine iterates through the virtual records of the supplied report data source, at report filling time. Depending on each section”s defined behavior, the engine then renders each report section when appropriate. For instance, the detail section is rendered for each record in the data source. When page breaks occur, the page header and page footer sections are rendered as needed. In JasperReports, terminology and report sections are also called as report bands. Sections are made up of one or more bands. These sections are filled repeatedly at report-generating time and prepare the final document. Main Sections A report template in JasperReports has the following main sections − <title></title> <pageheader></pageheader> <columnheader></columnheader> <groupheader></groupheader> <detail></detail> <groupfooter></groupfooter> <columnfooter></columnfooter> <pagefooter></pagefooter> <lastpagefooter></lastpagefooter> <summary></summary> <nodata></nodata> <background></background> The following table summarizes each of the sections − S.NO Section and Description 1 Title This section appears only once at the beginning of the report. 2 Page Header This section appears at the beginning of each page in the generated document. 3 Column Header This section appears at the beginning of each column in the generated document. If the report has only one column defined, then column header and footer sections are ignored. 4 Group Header This section is introduced by a report group (chapter Groups). Each time the grouping expression changes its value, the group header section is printed above the detail section. In case, if more than one group is defined, the group header is printed in the order of group definition. 5 Detail This section is repeated for each line of data supplied by the report”s data source. The detail section can be made of multiple bands. 6 Group Footer This section is introduced by a report group (chapter Groups). The group footer section is printed below the detail section before the value of the grouping expression changes. The group footer is always printed for the last line of data in data source. In case, if more than one group is defined, the group footer is printed in the reverse order of group definition. 7 Column Footer This section appears at the bottom of each column. If the report”s column count is 1, then column header and footer sections are ignored. 8 Page Footer This section appears at the bottom of each page. 9 Last Page Footer This section replaces the regular page footer on the last page of the report. In case, the summary section is also present, then this might not be the very last page of the document. This section is sometimes useful when summary information has to be displayed at the bottom of the last page. 10 Summary This section appears only once at the end of the report. 11 No Data This section is printed when the When No Data Print report property is set to No Data Section. If the <noData> section is defined in the report template, and if the data source is empty, then the <noData> section will be the only one taken into account at fill time, and its content will produce the report output. 12 Background The background section is displayed on every page and cannot overflow to the next page. Elements placed on this section are evaluated at page initialization time and are displayed in the background. All other page objects are displayed on top of the background objects. This section is useful for creating page watermarks. Section, Elements and Attribute Relation The following diagram shows the elements and attributes relationship in a section of a report. Section Elements All the above mentioned report sections are optional. But any report template will have at least one such section. Each of these sections contains a single <band> element as its only sub-element. A <band> can contain zero or more following sub-elements − <line>, <rectangle>, <ellipse>, <image>, <staticText>, <textField>, <subReport>, or <elementGroup> Each of these elements must contain a single <reportElement> as its first element (except elementGroup). A <reportElement> determines how data is laid out for that particular element. Unlike variables and parameters, report elements are not required to have a name, because normally you do not need to obtain any individual element inside a report template. The table below summarizes the attributes of <reportElement> − Attribute Description Valid Values x Specifies the x coordinate of the band element. An integer value indicating the x coordinate of the element in pixels. This attribute is required. y Specifies the y coordinate of the band element. An integer value indicating the y coordinate of the element in pixels. This attribute is required. width Specifies the width of the band element. An integer value indicating the element width in pixels. This attribute is required. height Specifies the height of the band element. An integer value indicating the element height in pixels. This attribute is required. key Unique identifier of band element. A unique string value. stretchType Specifies how does the element stretch when the containing band stretches NoStretch (default) − The element will not stretch. RelativeToTallestObject − The element will stretch to accommodate the tallest object in its group. RelativeToBand − The element will stretch to fit the band”s height. positionType Specifies the element”s position when the band stretches. Float − The element will move depending on the size of the surrounding elements. FixRelativeToTop (default) − The element will maintain a fixed position relative to the band”s top. FixRelativeToBottom − The element will maintain a fixed position relative to the band”s bottom. isPrintRepeatedValues Specifies if repeated values are printed. true (default) − Repeated values will be printed. false − Repeated values will not be printed. mode Specifies the background mode of the element Opaque, Transparent isRemoveLineWhenBlank Specifies if the element should be
JasperReports – Exporting
JasperReports – Exporting Reports ”; Previous Next We have seen in the previous chapter, how to print and view a JasperReport generated document. Here, we shall see how to transform or export these reports into other formats such as PDF, HTML, and XLS. Facade class net.sf.jasperreports.engine.JasperExportManager is provided to achieve this functionality. Exporting means transforming the JasperPrint object (.jrprint file) into different format. The following code (JasperReportExport.java) demonstrates the exporting process of the JasperReport document. The JasperExportManager provides methods to export a report into PDF, HTML, and XML only. To export to the XLS format, we have used the class net.sf.jasperreports.engine.export.JRXlsExporter. This code generates following three files − sample_report.pdf sample_report.html sample_report.xls Exporting to Other Formats Let”s write a report template. The contents of the JRXML file (C:toolsjasperreports-5.0.1testjasper_report_template.jrxml) are as below − <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE jasperReport PUBLIC “//JasperReports//DTD Report Design//EN” “http://jasperreports.sourceforge.net/dtds/jasperreport.dtd”> <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 = “jasper_report_template” language = “groovy” pageWidth = “595” pageHeight = “842” columnWidth = “555” leftMargin = “20” rightMargin = “20” topMargin = “20” bottomMargin = “20”> <queryString> <![CDATA[]]> </queryString> <field name = “country” class = “java.lang.String”> <fieldDescription><![CDATA[country]]></fieldDescription> </field> <field name = “name” class = “java.lang.String”> <fieldDescription><![CDATA[name]]></fieldDescription> </field> <columnHeader> <band height = “23”> <staticText> <reportElement mode = “Opaque” x = “0” y = “3” width = “535” height = “15” backcolor = “#70A9A9” /> <box> <bottomPen lineWidth = “1.0” lineColor = “#CCCCCC” /> </box> <textElement /> <text><![CDATA[]]> </text> </staticText> <staticText> <reportElement x = “414” y = “3” width = “121” height = “15” /> <textElement textAlignment = “Center” verticalAlignment = “Middle”> <font isBold = “true” /> </textElement> <text><![CDATA[Country]]></text> </staticText> <staticText> <reportElement x = “0” y = “3” width = “136” height = “15” /> <textElement textAlignment = “Center” verticalAlignment = “Middle”> <font isBold = “true” /> </textElement> <text><![CDATA[Name]]></text> </staticText> </band> </columnHeader> <detail> <band height = “16”> <staticText> <reportElement mode = “Opaque” x = “0” y = “0” width = “535” height = “14” backcolor = “#E5ECF9” /> <box> <bottomPen lineWidth = “0.25” lineColor = “#CCCCCC” /> </box> <textElement /> <text><![CDATA[]]> </text> </staticText> <textField> <reportElement x = “414” y = “0” width = “121” height = “15” /> <textElement textAlignment = “Center” verticalAlignment = “Middle”> <font size = “9” /> </textElement> <textFieldExpression class = “java.lang.String”> <![CDATA[$F{country}]]> </textFieldExpression> </textField> <textField> <reportElement x = “0” y = “0” width = “136” height = “15” /> <textElement textAlignment = “Center” verticalAlignment = “Middle” /> <textFieldExpression class = “java.lang.String”> <![CDATA[$F{name}]]> </textFieldExpression> </textField> </band> </detail> </jasperReport> Next, contents of the POJO file C:toolsjasperreports-5.0.1testsrccomtutorialspointDataBean.java are as given below − package com.tutorialspoint; public class DataBean { private String name; private String country; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } } The contents of the file C:toolsjasperreports-5.0.1testsrccomtutorialspointDataBeanList.java are as given below − package com.tutorialspoint; import java.util.ArrayList; public class DataBeanList { public ArrayList<DataBean> getDataBeanList() { ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>(); dataBeanList.add(produce(“Manisha”, “India”)); dataBeanList.add(produce(“Dennis Ritchie”, “USA”)); dataBeanList.add(produce(“V.Anand”, “India”)); dataBeanList.add(produce(“Shrinath”, “California”)); return dataBeanList; } /** * This method returns a DataBean object, * with name and country set in it. */ private DataBean produce(String name, String country) { DataBean dataBean = new DataBean(); dataBean.setName(name); dataBean.setCountry(country); return dataBean; } } Write a main class file JasperReportFill.java, which gets the java bean collection from the class (DataBeanList) and passes it to the JasperReports engine, to fill the report template. Save it to the directory C:toolsjasperreports-5.0.1testsrccomtutorialspoint. package com.tutorialspoint; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import net.sf.jasperreports.engine.export.JRXlsExporter; public class JasperReportFill { @SuppressWarnings(“unchecked”) public static void main(String[] args) { String sourceFileName = “c://tools/jasperreports-5.0.1/” + “test/jasper_report_template.jasper”; String printFileName = null; DataBeanList DataBeanList = new DataBeanList(); ArrayList<DataBean> dataList = DataBeanList.getDataBeanList(); JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList); Map parameters = new HashMap(); try { printFileName = JasperFillManager.fillReportToFile(sourceFileName, parameters, beanColDataSource); if (printFileName != null) { /** * 1- export to PDF */ JasperExportManager.exportReportToPdfFile(printFileName, “C://sample_report.pdf”); /** * 2- export to HTML */ JasperExportManager.exportReportToHtmlFile(printFileName, “C://sample_report.html”); /** * 3- export to Excel sheet */ JRXlsExporter exporter = new JRXlsExporter(); exporter.setParameter(JRExporterParameter.INPUT_FILE_NAME, printFileName); exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, “C://sample_report.xls”); exporter.exportReport(); } } catch (JRException e) { e.printStackTrace(); } } } Here, we have included the logic to export the jasper print file to pdf, html and xls format. Generating Reports Let”s compile and execute above files using our regular ANT build process. The build.xml file is as given below − <?xml version = “1.0” encoding = “UTF-8”?> <project name = “JasperReportTest” default = “executereport” basedir = “.”> <import file = “baseBuild.xml”/> <target name = “executereport” depends = “compile,compilereportdesing,run”> <echo message = “Im here”/> </target> <target name = “compilereportdesing” description = “Compiles the JXML file and produces the .jasper file.”> <taskdef name = “jrc” classname = “net.sf.jasperreports.ant.JRAntCompileTask”> <classpath refid = “classpath” /> </taskdef> <jrc destdir = “.”> <src> <fileset dir = “.”> <include name = “*.jrxml” /> </fileset> </src> <classpath refid = “classpath” /> </jrc> </target> </project> Go to the command prompt and then go to the directory C:toolsjasperreports-5.0.1test, where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill. The output is as follows − C:toolsjasperreports-5.0.1test>ant -Dmain-class=com.tutorialspoint.JasperReportFill Buildfile: C:toolsjasperreports-5.0.1testbuild.xml clean-sample: [delete] Deleting directory C:toolsjasperreports-5.0.1testclasses [delete] Deleting: C:toolsjasperreports-5.0.1testjasper_report_template.jasper [delete] Deleting: C:toolsjasperreports-5.0.1testjasper_report_template.jrprint compile: [mkdir] Created dir: C:toolsjasperreports-5.0.1testclasses [javac] C:toolsjasperreports-5.0.1testbaseBuild.xml:28: warning: ”includeantruntime” was not set, defaulting t [javac] Compiling 4 source files to C:toolsjasperreports-5.0.1testclasses compilereportdesing: [jrc] Compiling 1 report design files. [jrc] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory). [jrc] log4j:WARN Please initialize the log4j system properly. [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. [jrc] File : C:toolsjasperreports-5.0.1testjasper_report_template.jrxml … OK. run: [echo] Runnin class : com.tutorialspoint.JasperReportFill [java] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.extensions.ExtensionsEnvironment). [java] log4j:WARN Please initialize the log4j system properly. executereport: [echo] Im here BUILD SUCCESSFUL Total time: 32 seconds As the result of above execution, you will find three files sample_report.pdf, sample_report.html, sample_report.xls generated in the C: directory. Print Page Previous Next
JasperReports – Styles
Report Styles ”; Previous Next JasperReports has a feature <style> which helps to control text properties in a report template. This element is a collection of style settings declared at the report level. Properties like foreground color, background color, whether the font is bold, italic, or normal, the font size, a border for the font, and many other attributes are controlled by <style> element. Styles can extend other styles, and add to, or override properties of the parent style as well. Style Properties A <style> element has many attributes. Some of the most commonly used are listed in the table given below − S.NO Attribute and Description 1 name Is mandatory. It must be unique because it references the corresponding report style throughout the report. 2 isDefault Indicates whether this style is the document”s default style. 3 style Is a reference to the parent style. 4 mode Specifies the element”s transparency. Possible values are Opaque and Transparent. 5 forecolor Is the foreground color of object. 6 backcolor Is the background color of object. 7 fill Determines the fill pattern used to fill the object. At the moment, the single value allowed is Solid. 6 radius Specifies the radius of the rectangle”s corner arc. 7 scaleImage Specifies scale for the images only. Possible values: Clip, FillFrame, RetainShape, RealHeight, and RealSize. 8 hAlign Specifies the horizontal alignment. Possible values: Left, Center, Right, and Justified. 9 vAlign Specifies the vertical alignment. Possible values: Top, Middle, and Bottom. 10 rotation Specifies the element”s rotation. Possible values: None, Left, Right, and UpsideDown. 11 lineSpacing Specifies the line spacing between lines of text. Possible values: Single, 1_1_2, Double. 12 markup Specifies the markup style for styled texts. 13 fontName Specifies the font name. 14 fontSize Specifies the font size. 15 isBold Indicates if the font style is bold. 16 isItalic Indicates if the font style is italic. 17 isUnderline Indicates if the font style is underline. 18 isStrikeThrough Indicates if the font style is strikethrough. 19 pdfFontName Specifies the related PDF font name. 20 pdfEncoding Specifies the character encoding for the PDF output format. 22 isPdfEmbedded Indicates if the PDF font is embedded. 23 pattern Specifies the format pattern for formatted texts. 24 isBlankWhenNull Indicates if an empty string (whitespace) should be shown if the expression evaluates to null. Conditional Styles In some situations, a style should be applied only when certain condition is met (for example, to alternate adjacent row colors in a report detail section). This can be achieved using conditional styles. A conditional style has two elements − a Boolean condition expression a style The style is used only if the condition evaluates to true. Applying Styles to Report Elements Any type of report element can reference a report style definition using the style attribute. Hence, all the style properties declared by the style definition that are applicable to the current element will be inherited. To override the inherited values, style properties specified at the report element level can be used. Style Templates We can make a set of reports with a common look by defining the style at a common place. This common style template can then be referenced by the report templates. A style template is an XML file that contains one or more style definitions. Style template files used by convention the *.jrtx extension, but this is not mandatory. A style template contains following elements − <jasperTemplate> − This is the root element of a style template file. <template> − This element is used to include references to other template files. The contents of this element are interpreted as the location of the referred template file. <style> − This element is identical to the element with the same name from report design templates (JRXML files), with the exception that a style in a style template cannot contain conditional styles. This limitation is caused by the fact that conditional styles involve report expressions, and expressions can only be interpreted in the context of a single report definition. References to style templates are included in JRXML reports as <template> elements. The style templates are loaded at report fill time, and style name references are resolved once all the templates have been loaded. When loading style templates and resolving style names to styles, a tree/graph of style templates is created, the top of the tree being the set of styles defined in the report. On this tree, style name references are resolved to the last style that matches the name in a depth-first traversal. Example Let”s try out the conditional styles and style templates. Let”s add the <style> element alternateStyle to our existing report template (Chapter Report Designs). Based on the condition, font color changes to blue for even count. We have also included a style template “styles.jrtx”. The revised report template (jasper_report_template.jrxml) is as follows. Save it to C:toolsjasperreports-5.0.1test directory − <?xml version = “1.0”?> <!DOCTYPE jasperReport PUBLIC “//JasperReports//DTD Report Design//EN” “http://jasperreports.sourceforge.net/dtds/jasperreport.dtd”> <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 = “jasper_report_template” pageWidth = “595” pageHeight = “842” columnWidth = “515” leftMargin = “40” rightMargin = “40” topMargin = “50” bottomMargin = “50”> <template>”styles.jrtx”</template> <style name = “alternateStyle” fontName = “Arial” forecolor = “red”> <conditionalStyle> <conditionExpression> <![CDATA[new Boolean($V{countNumber}.intValue() % 2 == 0)]]> </conditionExpression> <style forecolor = “blue” isBold = “true”/> </conditionalStyle> </style> <parameter name = “ReportTitle” class = “java.lang.String”/> <parameter name = “Author” class = “java.lang.String”/> <queryString> <![CDATA[]]> </queryString> <field name = “country” class = “java.lang.String”> <fieldDescription><![CDATA[country]]></fieldDescription> </field> <field name = “name” class = “java.lang.String”> <fieldDescription><![CDATA[name]]></fieldDescription> </field> <variable name = “countNumber” class = “java.lang.Integer” calculation = “Count”> <variableExpression><![CDATA[Boolean.TRUE]]></variableExpression> </variable> <title> <band height = “70”> <line> <reportElement x = “0” y = “0” width = “515” height = “1”/> </line> <textField isBlankWhenNull = “true” bookmarkLevel = “1”> <reportElement x = “0” y = “10” width = “515” height = “30”/> <textElement textAlignment = “Center”> <font size = “22”/> </textElement> <textFieldExpression class = “java.lang.String”> <![CDATA[$P{ReportTitle}]]> </textFieldExpression> <anchorNameExpression><![CDATA[“Title”]]></anchorNameExpression> </textField> <textField isBlankWhenNull = “true”> <reportElement x = “0”
JasperReports – View & Print
Jasper Report – View & Print Reports ”; Previous Next The output of the report filling process JasperPrint objects can be viewed using a built-in viewer component, or printed, or exported to more popular document formats like PDF, HTML, RTF, XLS, ODT, CSV, or XML. Viewing and printing of the Jasper documents will be discussed in this chapter and exporting will be discussed in the next chapter i.e. ”Export Reports.” Viewing Reports JasperReport provides a built-in viewer for viewing the generated reports in its original format. It is a swing based component and other Java applications can integrate this component without having to export the documents to other formats in order to be viewed or printed. The net.sf.jasperreports.view.JRViewer class represents this visual component. This class can also be customized as per the application needs, by sub classing it. JasperReports also has a Swing application, which uses the visual component for viewing the reports. This application helps to view reports in the same format as *.jrprint is produced. This Swing application is implemented in the class net.sf.jasperreports.view.JasperViewer. To view reports using this class, we need to wrap it into an ANT target. Viewing the generated Report The following example demonstrates − how to view a report using the JasperViewer class − Let”s write a report template. The contents of the JRXML file (C:toolsjasperreports-5.0.1testjasper_report_template.jrxml) are as given below − <?xml version = “1.0” encoding = “UTF-8”?> <!DOCTYPE jasperReport PUBLIC “//JasperReports//DTD Report Design//EN” “http://jasperreports.sourceforge.net/dtds/jasperreport.dtd”> <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 = “jasper_report_template” language = “groovy” pageWidth = “595” pageHeight = “842” columnWidth = “555” leftMargin = “20” rightMargin = “20” topMargin = “20” bottomMargin = “20”> <queryString> <![CDATA[]]> </queryString> <field name = “country” class = “java.lang.String”> <fieldDescription><![CDATA[country]]></fieldDescription> </field> <field name = “name” class = “java.lang.String”> <fieldDescription><![CDATA[name]]></fieldDescription> </field> <columnHeader> <band height = “23”> <staticText> <reportElement mode = “Opaque” x = “0” y = “3” width = “535” height = “15” backcolor = “#70A9A9” /> <box> <bottomPen lineWidth = “1.0” lineColor = “#CCCCCC” /> </box> <textElement /> <text><![CDATA[]]> </text> </staticText> <staticText> <reportElement x = “414” y = “3” width = “121” height = “15” /> <textElement textAlignment = “Center” verticalAlignment = “Middle”> <font isBold = “true” /> </textElement> <text><![CDATA[Country]]></text> </staticText> <staticText> <reportElement x = “0” y = “3” width = “136” height = “15” /> <textElement textAlignment = “Center” verticalAlignment = “Middle”> <font isBold = “true” /> </textElement> <text><![CDATA[Name]]></text> </staticText> </band> </columnHeader> <detail> <band height = “16”> <staticText> <reportElement mode = “Opaque” x = “0” y = “0” width = “535” height = “14” backcolor = “#E5ECF9” /> <box> <bottomPen lineWidth = “0.25” lineColor = “#CCCCCC” /> </box> <textElement /> <text><![CDATA[]]> </text> </staticText> <textField> <reportElement x = “414” y = “0” width = “121” height = “15” /> <textElement textAlignment = “Center” verticalAlignment = “Middle”> <font size = “9” /> </textElement> <textFieldExpression class = “java.lang.String”> <![CDATA[$F{country}]]> </textFieldExpression> </textField> <textField> <reportElement x = “0” y = “0” width = “136” height = “15” /> <textElement textAlignment = “Center” verticalAlignment = “Middle” /> <textFieldExpression class = “java.lang.String”> <![CDATA[$F{name}]]> </textFieldExpression> </textField> </band> </detail> </jasperReport> Next, let”s pass a collection of Java data objects (Java beans), to the JasperReports Engine, to fill this compiled report. Write a POJO DataBean.java, which represents the data object (Java bean). This class defines two String objects i.e. ”name” and ”country.” Save it to the directory C:toolsjasperreports-5.0.1testsrccomtutorialspoint. package com.tutorialspoint; public class DataBean { private String name; private String country; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } } Write a class DataBeanList.java, which has business logic to generate a collection of java bean objects. This is further passed to the JasperReports engine, to generate the report. Here, we are adding 4 DataBean objects in the List. Save it to the directory C:toolsjasperreports-5.0.1testsrccomtutorialspoint. package com.tutorialspoint; import java.util.ArrayList; public class DataBeanList { public ArrayList<DataBean> getDataBeanList() { ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>(); dataBeanList.add(produce(“Manisha”, “India”)); dataBeanList.add(produce(“Dennis Ritchie”, “USA”)); dataBeanList.add(produce(“V.Anand”, “India”)); dataBeanList.add(produce(“Shrinath”, “California”)); return dataBeanList; } /** * This method returns a DataBean object, * with name and country set in it. */ private DataBean produce(String name, String country) { DataBean dataBean = new DataBean(); dataBean.setName(name); dataBean.setCountry(country); return dataBean; } } Write a main class file JasperReportFill.java, which gets the java bean collection from the class (DataBeanList) and passes it to the JasperReports engine, to fill the report template. Save it to the directory C:toolsjasperreports-5.0.1testsrccomtutorialspoint. package com.tutorialspoint; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; public class JasperReportFill { @SuppressWarnings(“unchecked”) public static void main(String[] args) { String sourceFileName = “c://tools/jasperreports-5.0.1/test/jasper_report_template.jasper”; DataBeanList DataBeanList = new DataBeanList(); ArrayList<DataBean> dataList = DataBeanList.getDataBeanList(); JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList); Map parameters = new HashMap(); try { JasperFillManager.fillReportToFile( sourceFileName, parameters, beanColDataSource); } catch (JRException e) { e.printStackTrace(); } } } Let”s write a target viewFillReport to the build.xml file. The build.xml file is as follows − The import file – baseBuild.xml is picked from chapter Environment Setup and should be placed in the same directory as the build.xml. <?xml version = “1.0” encoding = “UTF-8”?> <project name = “JasperReportTest” default = “viewFillReport” basedir = “.”> <import file = “baseBuild.xml”/> <target name = “viewFillReport” depends = “compile,compilereportdesing,run” description = “Launches the report viewer to preview the report stored in the .JRprint file.”> <java classname = “net.sf.jasperreports.view.JasperViewer” fork = “true”> <arg value = “-F${file.name}.JRprint” /> <classpath refid = “classpath” /> </java> </target> <target name = “compilereportdesing” description = “Compiles the JXML file and produces the .jasper file.”> <taskdef name = “jrc” classname = “net.sf.jasperreports.ant.JRAntCompileTask”> <classpath refid = “classpath” /> </taskdef> <jrc destdir = “.”> <src> <fileset dir = “.”> <include name = “*.jrxml” /> </fileset> </src> <classpath refid = “classpath” /> </jrc> </target> </project> Next, let”s open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFillReport is the default target). As a result, we see a JasperViewer window as