Report Scriptlets ”; Previous Next We have seen in our previous chapters, data displayed on the report is usually fetched from report parameters and report fields. This data can be processed using the report variables and their expressions. There are situations when a complex functionality cannot be achieved easily using report expressions or variables. Examples of this may be complex String manipulations, building of Maps, or Lists of objects in memory or manipulations of dates using 3rd party Java APIs. For such situations, JasperReports provides us with a simple and powerful means of doing this with Scriptlets. Scriptlets are sequences of Java code that are executed every time a report event occurs. Values of report variables can be affected through scriptlets. Scriptlet Declaration We can declare a scriptlet in two ways − Using <scriptlet> element. This element has name attribute and class attribute. The class attribute should specify the name of the class, which extends JRAbstractScriptlet class. The class must be available in the classpath at report filling time and must have an empty constructor, so that the engine can instantiate it on the fly. Using the attribute scriptletClass of the element <jasperReport>, in the report template (JRXML). By setting this attribute with fully qualified name of scriptlet (including the entire package name), we indicate that we want to use a scriptlet. The scriptlet instance, created with this attribute, acts like the first scriptlet in the list of scriptlets and has the predefined name REPORT. Scriptlet class A scriptlet is a java class, which must extend either of the following classes − net.sf.jasperreports.engine.JRAbstractScriptlet − This class contains a number of abstract methods that must be overridden in every implementation. These methods are called automatically by JasperReports at the appropriate moment. Developer must implement all the abstract methods. net.sf.jasperreports.engine.JRDefaultScriptlet − This class contains default empty implementations of every method in JRAbstractScriptlet. A developer is only required to implement those methods he/she needs for his/her project. The following table lists the methods in the above class. These methods will be called by the report engine at the appropriate time, during report filling phase. S.NO Method and Description 1 public void beforeReportInit() Called before report initialization. 2 public void afterReportInit() Called after report initialization. 3 public void beforePageInit() Called before each page is initialized. 4 public void afterPageInit() Called after each page is initialized. 5 public void beforeColumnInit() Called before each column is initialized. 6 public void afterColumnInit() Called after each column is initialized. 7 public void beforeGroupInit(String groupName) Called before the group specified in the parameter is initialized. 8 public void afterGroupInit(String groupName) Called after the group specified in the parameter is initialized. 9 public void beforeDetailEval() Called before each record in the detail section of the report is evaluated. 10 public void afterDetailEval() Called after each record in the detail section of the report is evaluated. Any number of scriptlets can be specified per report. If no scriptlet is specified for a report, the engine still creates a single JRDefaultScriptlet instance and registers it with the built-in REPORT_SCRIPTLET parameter. We can add any additional methods that we need to our scriptlets. Reports can call these methods by using the built-in parameter REPORT_SCRIPTLET. Global Scriptlets We can associate scriptlets in another way to reports, which is by declaring the scriptlets globally. This makes the scriptlets apply to all reports being filled in the given JasperReports deployment. This is made easy by the fact that scriptlets can be added to JasperReports as extensions. The scriptlet extension point is represented by the net.sf.jasperreports.engine.scriptlets.ScriptletFactory interface. JasperReports will load all scriptlet factories available through extensions at runtime. Then, it will ask each one of them for the list of scriptlets instances that they want to apply to the current report that is being run. When asking for the list of scriptlet instances, the engine gives some context information that the factory could use in order to decide, which scriptlets actually apply to the current report. Report Governors Governors are just an extension of global scriptlets that enable us to tackle a problem of report engine entering infinite loop at runtime, while generating reports. Invalid report templates cannot be detected at design time, because most of the time, the conditions for entering the infinite loops depend on the actual data that is fed into the engine at runtime. Report Governors help in deciding whether a certain report has entered an infinite loop and they can stop it. This prevents resource exhaustion for the machine that runs the report. JasperReports has two simple report governors that would stop a report execution based on a specified maximum number of pages or a specified timeout interval. They are − net.sf.jasperreports.governors.MaxPagesGovernor − This is a global scriptlet that is looking for two configuration properties to decide if it applies or not to the report currently being run. The configuration properties are − net.sf.jasperreports.governor.max.pages.enabled=[true|false] net.sf.jasperreports.governor.max.pages=[integer] net.sf.jasperreports.governors.TimeoutGovernor− This is also a global scriptlet that is looking for the following two configuration properties to decide if it applies or not. The configuration properties are − net.sf.jasperreports.governor.timeout.enabled=[true|false] net.sf.jasperreports.governor.timeout=[milliseconds] The properties for both governors can be set globally, in the jasperreports.properties file, or at report level, as custom report properties. This is useful because different reports can have different estimated size or timeout limits and also because you might want turn on the governors for all reports, while turning it off for some, or vice-versa. Example Let”s write a scriptlet class (MyScriptlet). The contents of file C:toolsjasperreports-5.0.1testsrccomtutorialspointMyScriptlet.java are as follows − package com.tutorialspoint; import net.sf.jasperreports.engine.JRDefaultScriptlet; import net.sf.jasperreports.engine.JRScriptletException; public class MyScriptlet extends JRDefaultScriptlet { public void afterReportInit() throws JRScriptletException{ System.out.println(“call afterReportInit()”); // this.setVariableValue(“AllCountries”, sbuffer.toString()); this.setVariableValue(“someVar”, new String(“This variable value was modified by the scriptlet.”)); } public String hello() throws JRScriptletException { return “Hello! I”m the report”s scriptlet object.”; } } Details of the above scriptlet class are as follows − In the afterReportInit method, we set a value to the variable “someVar” this.setVariableValue(“someVar”, new String(“This variable value was modified by the scriptlet.”)). At
Category: jasper Reports
JasperReports – Getting Started ”; Previous Next What is a Report A report is a meaningful, well-defined, and summarized presentation of information. Usually, the routine activities are automated and data summarized into a decision-supporting “Reports”. Reports represent usual messy data into charts, graphs, and other forms of graphical representations. Report Template Generally, the following layout is adopted to generate reports by most of the commercial report generating tools. TITLE PAGEHEADER COLUMNHEADER DETAIL COLUMNFOOTER PAGEFOOTER SUMMARY Following are the descriptions of each element mentioned in the diagram − S.NO Element and Description 1 title Title contains the ”Title” of the report. It appears only once at the very beginning of the report, for example, “Tutorials Point Report.” 2 pageHeader PageHeader may contain date and time information and/or organization name. This appears at the top of each page. 3 columnHeader ColumnHeader lists the names of those specific fields, which you want to display in the report, for example, “Author Name,” “Starting Hour,” “Finishing Hour,” “Hours Worked,” “Date,” etc. 4 detail Detail is the part where entries of the specific fields (listed in columnHeader) are shown, for example “Manisha”, “9:00”, “18:00”, “9”, “10.02.2013.” 5 columnFooter ColumnFooter may display summation of any of the field, for example, “Total Hours Worked: “180.” 6 pageFooter PageFooter may contain page count information. It appears at the bottom of each page, for example, “1/23.” 7 summary Summary contains information inferred from “detail” part, for example, after listing the number of hours, worked by each author, total hours worked by each author can be put in visual chart like pie chart, graph, etc. for better comparison. JasperReports Following are the common troubles faced during the report development − Core changes − Usually, reflect the business changes or enhancements it is required to change the core logic of the report. Results exporting − There are a wide range of formats, which your report can be exported to, such as: HTML, Text, PDF, MS Excel, RTF, ODT, Comma-separated values, XML, or image. Complicated reports − sub-reports and cross-tabs reports are good example. Charts reports − Visual charts for example, Graph, Pie, XY Line, Bar, Meter, and Time series. To remove the overhead of the above mentioned points and to facilitate the reporting process, a lot of frameworks, tools, libraries, and 3rd parties applications were introduced. JasperReports is one of them. JasperReports is an open source java reporting engine. It is Java based and doesn”t have its own expression syntax. JasperReports has the ability to deliver rich content onto the screen, to the printer, or into PDF, HTML, XLS, RTF, ODT, CSV, TXT, and XML files. As it is not a standalone tool, it cannot be installed on its own. Instead, it is embedded into Java applications by including its library in the application”s CLASSPATH. JasperReports is a Java class library, and is not meant for the end users, but rather is targeted towards Java developers who need to add reporting capabilities to their applications. Features of JasperReports Some of the significant features of JasperReports are − It has a flexible report layout. It can present data either textually or graphically. Developers can supply data in multiple ways. It can accept data from the multiple data sources. It can generate watermarks (A watermark is like a secondary image that is laid over the primary image). It can generate sub reports. It is capable of exporting reports in a variety of formats. Print Page Previous Next Advertisements ”;
JasperReports – Fonts
Report Fonts ”; Previous Next A report contains text elements and each of these can have its own font settings. These settings can be specified using the <font> tag available in the <textElement> tag. A report can define a number of fonts. Once defined, they can be used as default or base font settings for other font definitions throughout the entire report. Report Fonts A report font is a collection of font settings, declared at the report level. A report font can be reused throughout the entire report template when setting the font properties of text elements. Report fonts are now deprecated. Do not use <reportFont/> elements declared within the document itself. Use the <style/> element instead. Font Attributes Table below summarizes the main attributes of the <font> element − S.NO Attribute and Description 1 fontName The font name, which can be the name of a physical font, a logical one, or the name of a font family from the registered JasperReports font extensions. 2 size The size of the font measured in points. It defaults to 10. 3 isBold The flag specifying if a bold font is required. It defaults to false. 4 isItalic The flag specifying if an italic font is required. It defaults to false. 5 isUnderline The flag specifying if the underline text decoration is required. It defaults to false. 6 isStrikeThrough The flag specifying if the strikethrough text decoration is required. It defaults to false. 7 pdfFontName The name of an equivalent PDF font required by the iText library when exporting documents to PDF format. 8 pdfEncoding The equivalent PDF character encoding, also required by the iText library. 9 isPdfEmbedded The flag that specifies whether the font should be embedded into the document itself. It defaults to false. If set to true, helps view the PDF document without any problem. Font Types In JasperReports fonts can be categorized as − Logical Fonts − Five font types, which have been recognized by the Java platform since version 1.0, are called logical fonts. These are − Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical fonts are not actual font libraries that are installed anywhere on the system. They are merely font type names recognized by the Java runtime. These must be mapped to some physical font that is installed on the system. Physical Fonts − These fonts are the actual font libraries consisting of, for example, TrueType or PostScript Type 1 fonts. The physical fonts may be Arial, Time, Helvetica, Courier, or any number of other fonts, including international fonts. Font Extensions − The JasperReports library can make use of fonts registered on-the-fly at runtime, through its built-in support for font extensions. A list of font families can be made available to the JasperReports using font extension. These are made out of similarly looking font faces and supporting specific locales. As described in the table above we need to specify in the attribute fontName the name of a physical font, the name of a logical font, or the name of a font family from the registered JasperReports font extensions. PDF Font Name JasperReports library uses the iText library, when exporting reports to PDF(Portable Document Format). PDF files can be viewed on various platforms and will always look the same. This is partially because in this format, there is a special way of dealing with fonts. fontName attribute is of no use when exporting to PDF. Attribute pdfFontName exist where we need to specify the font settings. The iText library knows how to deal with built-in fonts and TTF files and recognizes the following built-in font names − Courier Courier-Bold Courier-BoldOblique Courier-Oblique Helvetica Helvetica-Bold Helvetica-BoldOblique Helvetica-Oblique Symbol Times-Roman Times-Bold Times-BoldItalic Times-Italic ZapfDingbats As per iText library pre-requisite, to work with fonts, we need to specify one of the following as the font name − A built-in font name from the above list. The name of a TTF (True Type Font) file, which it can locate on disk. The real name of the font, provided that the TTF file containing the font has been previously registered with iText or that an alias was defined when the font was registered. Based on the above pre-requisites, the pdfFontName attribute can contain one of the following values − The name of a built-in PDF font from the above list. The name of a TTF file that can be located on disk at runtime when exporting to PDF. The real name of a registered font. The suffix of the key (the part after net.sf.jasperreports.export.pdf.font) for a font registered with iText as a font file. Default Fonts and Inheritance Each text element inherits font and style attributes from its parent element, which in turn inherits these attributes from its parent. If no styles and/or fonts are defined for elements, the default style (and/or font – but this is now deprecated) declared in the <jasperReport/> root element will be applied. Defining default styles or fonts in JasperReports is not mandatory. If no font is defined for a given element, the engine looks either for the inherited font attributes, or, if no attributes are found on this way, it looks for the net.sf.jasperreports.default.font.name property in the /src/default.jasperreports.properties file. Its value defines the name of the font family to be used when font properties are not explicitly defined for a text element or inherited from its parent. The main default font properties and their values defined in the /src/default.jasperreports.properties file are in the table below − Property Description net.sf.jasperreports.default.font.name=SansSerif The default font name. net.sf.jasperreports.default.font.size=10 The default font size. net.sf.jasperreports.default.pdf.font.name=Helvetica The default PDF font. net.sf.jasperreports.default.pdf.encoding=Cp1252 The default PDF character encoding. net.sf.jasperreports.default.pdf.embedded=false By default PDF fonts are not embedded. Example To demonstrate using fonts and font attributes in order to get a particular text appearance, let”s write new report template (jasper_report_template.jrxml). The contents of the JRXML are as below. Save it to C:toolsjasperreports-5.0.1test directory. Here, we will display a text in the title of the report in various font formats. <?xml version = “1.0” encoding
JasperReports – Compiling Report Design ”; Previous Next We have generated the JasperReport template (JRXML file) in the previous chapter. This file cannot be used directly to generate reports. It has to be compiled to JasperReport” native binary format, called Jasper file. On compiling, we transform JasperDesign object into JasperReport object − Interface net.sf.jasperreports.engine.design.JRCompiler plays a central role during compilation. This interface has several implementations depending on the language used for report expressions, which can be written in Java, Groovy, JavaScript, or any other scripting language as long as compiler implementation can evaluate it at runtime. We can compile JRXML file in the following two ways − Programmatic compilation. Compilation through ANT task. Programmatic Compilation of JRXML JasperReports API offers a facade class net.sf.jasperreports.engine.JasperCompileManager for compiling a JasperReport. This class consists of several public static methods for compiling report templates. The source of templates can be files, input streams and/or, memory objects. The contents of the JRXML file (jasper_report_template.jrxml) are as follows. It is saved at directory C:toolsjasperreports-5.0.1test − <?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> The following code demonstrates compilation of the above jasper_report_template.jrxml file. package com.tutorialspoint; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperCompileManager; public class JasperReportCompile { public static void main(String[] args) { String sourceFileName = “C://tools/jasperreports-5.0.1/test” + “/jasper_report_template.jrxml”; System.out.println(“Compiling Report Design …”); try { /** * Compile the report to a file name same as * the JRXML file name */ JasperCompileManager.compileReportToFile(sourceFileName); } catch (JRException e) { e.printStackTrace(); } System.out.println(“Done compiling!!! …”); } } Template Compilation As next step, let”s save above content in the file C:toolsjasperreports-5.0.1testsrccomtutorialspointJasperReportCompile.java and import the baseBuild.xml in the build.xml file as below. The baseBuild.xml already has the compile and run targets − <?xml version = “1.0” encoding = “UTF-8”?> <project name = “JasperReportTest” default = “run” basedir = “.”> <import file = “baseBuild.xml”/> </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.JasperReportCompile as − C:toolsjasperreports-5.0.1test>ant -Dmain-class = com.tutorialspoint.JasperReportCompile Buildfile: C:toolsjasperreports-5.0.1testbuild.xml compile: [javac] C:toolsjasperreports-5.0.1testbaseBuild.xml:27: warning: ”includeantruntime” was not set, defaulting to build.sysclasspath=last;set to false for repeatable builds [javac] Compiling 1 source file to C:toolsjasperreports-5.0.1testclasses run: [echo] Runnin class : com.tutorialspoint.JasperReportCompile [java] Compiling Report Design … [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. [java] Done compiling!!! … BUILD SUCCESSFUL Total time: 8 seconds As a result of above compilation, you will see that template file jasper_report_template.jasper got generated in C:toolsjasperreports-5.0.1test directory. Preview Compiled Report Template The net.sf.jasperreports.view.JasperDesignViewer can be used to preview compiled report templates and JRXML templates. To move further, let”s add a new target viewDesign to the above build.xml file, which will allow us to preview the compiled report. Below is the revised build.xml − 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 = “viewDesign” basedir = “.”> <import file = “baseBuild.xml” /> <target name = “viewDesign” description=”Design viewer is launched to preview the compiled report design.”> <java classname = “net.sf.jasperreports.view.JasperDesignViewer” fork = “true”> <arg value = “-F${file.name}.jasper” /> <classpath refid = “classpath” /> </java> </target> </project> Let”s execute the command − ant (viewDesign is the default target) at command prompt. JasperDesignViewer window opens up displaying the Jasper file as below − Compilation through ANT Task As report template compilation is more like a design time job than a runtime job, JasperReport library has a custom ANT task. For certain situations, when JRXML file is created at runtime, we can”t use this ANT task. The custom ANT task is called JRC and is implemented by the class: net.sf.jasperreports.ant.JRAntCompileTask. Its syntax and behavior are very similar to the built-in <javac> ANT task. Template Compilation Let”s add new target compilereportdesing to our existing build.xml. Here, the source folder is specified using a nested <src> tag with the filesets. The nested source tag allows compiling report templates that are scattered through many different locations and are not grouped under a single root report source folder. Below is the revised build.xml − <?xml version = “1.0” encoding = “UTF-8”?> <project name = “JasperReportTest” default = “compilereportdesing” basedir = “.”> <import file = “baseBuild.xml” /> <target name = “viewDesign” description = “Design viewer is launched to
JasperReports – Discussion
Discuss JasperReports ”; Previous Next 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. Print Page Previous Next Advertisements ”;
JasperReports – Useful Resources ”; Previous Next The following resources contain additional information on JasperReports. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Learn Crystal Reports Online 38 Lectures 2 hours Tutorialspoint More Detail Access Forms and Reports 3 Lectures 2.5 hours Thomas Fragale More Detail Learn Apache Spark to Generate Weblog Reports for Websites 28 Lectures 1 hours Bigdata Engineer More Detail Basic Microsoft Visio Course with Practice Exercises 43 Lectures 5.5 hours Stephen Saxton More Detail SAP FICO (Finance And Controlling) Training Course Most Popular 41 Lectures 31 hours Uplatz More Detail Microsoft Ads Training-Traffic & Profits:Step-By Step Course 15 Lectures 1 hours Prof. Paul Cline, Ed.D More Detail Print Page Previous Next Advertisements ”;
Create SubReports ”; Previous Next Subreports are one of the nice features of the JasperReports. This feature allows incorporating a report within another report, that is, one report can be a subreport of another. Subreports help us keep report designs simple, as we can create many simple reports and encapsulate them into a master report. Subreports are compiled and filled just like normal reports. Any report template can be used as a subreport when incorporated into another report template, without anything changed inside (of the report template). Subreports are like normal report templates. They are in fact net.sf.jasperreports.engine.JasperReport objects, which are obtained after compiling a net.sf.jasperreports.engine.design.JasperDesign object. <subreport> Element A <subreport> element is used when introducing subreports into master reports. Here is the list of sub-elements in the <subreport> JRXML element. <reportElement> <parametersMapExpression> − This is used to pass a map containing report parameters to the subreport. The map is usually obtained from a parameter in the master report, or by using the built-in REPORTS_PARAMETERS_MAP parameter to pass the parent report”s parameters to the subreport. This expression should always return a java.util.Map object in which the keys are the parameter names. <subreportParameter> − This element is used to pass parameters to the subreport. It has an attribute name, which is mandatory. <connectionExpression > − This is used to pass a java.sql.Connection to the subreport. It is used only when the subreport template needs a database connection during report filling phase. <dataSourceExpression> − This is used to pass a datasource to the subreport. This datasource is usually obtained from a parameter in the master report or by using the built-in REPORT_DATA_SOURCE parameter to pass the parent report”s datasource to the subreport. The elements (connectionExpression and dataSourceExpression) cannot be present at the same time in a <subreport> element declaration. This is because we cannot supply both a data source and a connection to the subreport. We must decide on one of them and stick to it. <returnValue> − This is used to assign the value of one of the subreport”s variables to one of the master report”s variables. This sub element has attributes as follows − subreportVariable − This attribute specifies the name of the subreport variable whose value is to be returned. toVariable − This attribute specifies the name of the parent report variable whose value is to be copied/incremented with the value from the subreport. calculation − This attribute can take values : Nothing, Count, DistinctCount, Sum, Average, Lowest, Highest, StandardDeviation, Variance. Default value for attribute calculation is “Nothing”. incrementerFactoryClass − This attribute specifies the factory class for creating the incrementer instance. <subreportExpression> − This indicates where to find the compiled report template for the subreport. This element has a class attribute. The class attribute can take any of these values:java.lang.String, java.io.File, java.net.URL, java.io.InputStream, net.sf.jasperreports.engine.JasperReport. Default value is java.lang.String. isUsingCache − This is an attribute of the <subreport> element. This is a Boolean, when set to true, the reporting engine will try to recognize previously loaded subreport template objects, using their specified source. This caching functionality is available only for subreport elements that have expressions returning java.lang.String objects as the subreport template source, representing file names, URLs, or classpath resources. Example Let take up a simple example to demonstrate creation of subreports using JRDataSource. Let”s first write two new report templates, one being subreport and the other Master report. The contents of the subreport (address_report_template.jrxml) template is as given below. Save it to C:toolsjasperreports-5.0.1test directory. <?xml version = “1.0” encoding = “UTF-8”?> <jasperReport xmlns = “http://jasperreports.sourceforge.net/jasperreports” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd” name = “address_report_template” pageWidth = “175” pageHeight = “842” columnWidth = “175” leftMargin = “0” rightMargin = “0” topMargin = “0” bottomMargin = “0”> <field name = “city” class = “java.lang.String”/> <field name = “street” class = “java.lang.String”/> <background> <band splitType = “Stretch”/> </background> <title> <band height = “20” splitType = “Stretch”> <staticText> <reportElement x = “0” y = “0” width = “100” height = “20”/> <textElement> <font size = “14” isBold = “true”/> </textElement> <text><![CDATA[Addresses]]></text> </staticText> </band> </title> <pageHeader> <band height = “12” splitType = “Stretch”/> </pageHeader> <columnHeader> <band height = “12” splitType = “Stretch”/> </columnHeader> <detail> <band height = “27” splitType = “Stretch”> <textField> <reportElement x = “0” y = “0” width = “120” height = “20”/> <textElement> <font size = “12” isBold = “true”/> </textElement> <textFieldExpression class = “java.lang.String”> <![CDATA[$F{city}+” Address:”]]> </textFieldExpression> </textField> <textField isStretchWithOverflow = “true”> <reportElement x = “120” y = “0” width = “435” height = “20”/> <textElement> <font size = “12”/> </textElement> <textFieldExpression class = “java.lang.String”> <![CDATA[$F{street}]]> </textFieldExpression> </textField> </band> </detail> <columnFooter> <band height = “8” splitType = “Stretch”/> </columnFooter> <pageFooter> <band height = “11” splitType = “Stretch”/> </pageFooter> <summary> <band height = “9” splitType = “Stretch”/> </summary> </jasperReport> As we use a data source, we need to write a corresponding POJO file SubReportBean.java as shown below. Save it to directory C:toolsjasperreports-5.0.1testsrccomtutorialspoint − package com.tutorialspoint; public class SubReportBean { private String city; private String street; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } } Here, we have declared two fields ”city” and ”street” and respective getter and setter methods are defined. Now, let”s update our existing DataBean file. We will add a new field subReportBeanList, which is a java.util.List. This field will hold the list of SubReportBean objects. The contents of the file DataBean are as below. Save it to directory C:toolsjasperreports-5.0.1testsrccomtutorialspoint. package com.tutorialspoint; import java.util.List; public class DataBean { private String name; private String country; private List<SubReportBean> subReportBeanList; 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; } public List<SubReportBean> getSubReportBeanList() { return subReportBeanList; } public void setSubReportBeanList(List<SubReportBean> subReportBeanList) { this.subReportBeanList = subReportBeanList; } } Let”s now update the file C:toolsjasperreports-5.0.1testsrccomtutorialspointDataBeanList.java. The contents of this file are as −
JasperReports – Groups
Report Groups ”; Previous Next Groups in JasperReports help to organize data on report in a logical manner. A report group represents a sequence of consecutive records in the data source, which have something in common, such as the value of a certain report fields. A report group is defined by the <group> element. A report can have any number of groups. Once declared, groups can be referred throughout the report. A report group has three elements − Group expression − This indicates the data that must change to start a new data group. Group header section − Helps place label at the beginning of the grouped data. Group footer section − Helps place label at the end of the grouped data. During the iteration through the data source at report-filling time if the value of the group expression changes, a group rupture occurs and the corresponding <groupFooter> and <groupHeader> sections are inserted in the resulting document. Report group mechanism does not perform any sorting on the data supplied by the data source. Data grouping works as expected only when the records in the data source are already ordered according to the group expressions used in the report. Group Attributes The <group> element contains attributes that allow us to control how grouped data is laid out. The attributes are summarized in table below − S.NO Attribute and Description 1 name This is mandatory. It references the group in report expressions by name. It follows the same naming conventions that we mentioned for the report parameters, fields, and report variables. It can be used in other JRXML attributes when you want to refer a particular report group. 2 isStartNewColumn When set to true, each data group will begin on a new column. Default value is false. 3 isStartNewPage When set to true, each data group will begin on a new page. Default value is false. 4 isResetPageNumber When set to true, the report page number will be reset every time a new group starts. Default value is false. 5 isReprintHeaderOnEachPage When set to true, the group header will be reprinted on every page. Default value is false. 6 minHeightToStartNewPage Defines minimum amount of vertical space needed at the bottom of the column in order to place the group header on the current column. The amount is specified in report units. 7 footerPosition Renders position of the group footer on the page, as well as its behavior in relation to the report sections that follow it.Its value can be: Normal, StackAtBottom, ForceAtBottom, and CollateAtBottom. Default value is Normal. 8 keepTogether When set to true, prevents the group from splitting on its first break attempt. Example Let”s add a group (CountryGroup) to existing report template (Chapter Report Designs). Occurrence of each country is counted and the count is displayed as the group footer. In the group header, the count of each record is prefixed. 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”> <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> <sortField name = “country” order = “Descending”/> <sortField name = “name”/> <variable name = “CountryNumber” class = “java.lang.Integer” incrementType = “Group” incrementGroup = “CountryGroup” calculation = “Count”> <variableExpression><![CDATA[Boolean.TRUE]]></variableExpression> </variable> <group name = “CountryGroup” minHeightToStartNewPage = “60”> <groupExpression><![CDATA[$F{country}]]></groupExpression> <groupHeader> <band height = “20”> <textField evaluationTime = “Group” evaluationGroup = “CountryGroup” bookmarkLevel = “1”> <reportElement mode = “Opaque” x = “0” y = “5” width = “515” height = “15” backcolor = “#C0C0C0″/> <box leftPadding = “10”> <bottomPen lineWidth = “1.0”/> </box> <textElement/> <textFieldExpression class = “java.lang.String”> <![CDATA[” ” + String.valueOf($V{CountryNumber}) + “. ” + String.valueOf($F{country})]]> </textFieldExpression> <anchorNameExpression> <![CDATA[String.valueOf($F{country})]]> </anchorNameExpression> </textField> </band> </groupHeader> <groupFooter> <band height = “20”> <staticText> <reportElement x = “400” y = “1” width = “60” height = “15”/> <textElement textAlignment = “Right”/> <text><![CDATA[Count :]]></text> </staticText> <textField> <reportElement x = “460” y = “1” width = “30” height = “15”/> <textElement textAlignment = “Right”/> <textFieldExpression class = “java.lang.Integer”> <![CDATA[$V{CountryGroup_COUNT}]]> </textFieldExpression> </textField> </band> </groupFooter> </group> <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” y = “40” width = “515” height = “20”/> <textElement textAlignment = “Center”> <font size = “10”/> </textElement> <textFieldExpression class = “java.lang.String”> <![CDATA[$P{Author}]]> </textFieldExpression> </textField> </band> </title> <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 =
Creating Charts ”; Previous Next Earlier people had to rely on scriptlets to gather the chart data and render the chart using an image element in the report template. JasperReports makes it simple now, as it has a built-in support for charts using the new chart component. Using a new chart component, user needs to apply only the visual settings and define expressions that will help build the chart dataset. JasperReports uses JFreeChart as the underlying charting library. When configuring a new chart component, following three components are involved − The overall chart component. The chart dataset (which groups chart data-related settings). The chart plot (which groups visual settings related to the way the chart items are rendered). JasperReports currently supports the following types of charts: Pie, Pie 3D, Bar, Bar 3D, XY Bar, Stacked Bar, Stacked Bar 3D, Line, XY Line, Area, XY Area, Stacked Area, Scatter, Bubble, Time Series, High-Low-Open-Close, Candlestick, Multiple Axis, Meter, Thermometer, and Gantt. Chart Properties Charts are normal report elements, so they share some of their properties with all the other report elements. There is a JRXML element called <chart>, used to create all type of charts. This element groups special chart-specific settings that apply to all types of charts. Chart Sub-Elements The sub-elements of <chart> element are − <reportElement> − These are displayable objects like static texts, text fields, images, lines, and rectangles that you put in your report template sections. <Box> − This element is used to surround charts by a border that”s customizable on each side. <chartTitle> − This element is used to place the title of the chart. The position attribute decides the title position of the chart in the report. This element has attributes – Position (Values could be Top, Bottom, Left, Right. Deafult value is Top), color. <chartTitle> has font and titleExpression as subelements. <chartSubtitle> − This element is used to place the subtitle of the chart. This element has attribute – color. <chartSubtitle> has font and subtitleExpression as subelements. <chartLegend> − The element can control the font-related properties as well as the text color and the background color of the chart legend using this element. This element has attributes – textColor and backgroundColor. <anchorNameExpression> − This element creates the target for the anchor. <hyperlinkReferenceExpression> − This element contains a report expression indicating the name of the external resource (usually a URL). <hyperlinkAnchorExpression> − Hyperlink points to an anchor in an external resource. <hyperlinkPageExpression> − Hyperlink points to a page in the current report. <hyperlinkTooltipExpression> − This element controls the ToolTip of hyperlink. The type of the expression should be java.lang.String. <hyperlinkParameter> − This element when present generates a final hyperlink depending on the parameter values. Chart attributes Attributes in the <chart> element available for all chart types are − isShowLegend − This attribute is used to determine, if a chart legend will be displayed on the report. Values could be true, or false. Default value is true. evaluationTime − Determines when the chart”s expression will be evaluated. Values could be Now, Report, Page, Column, Group, Band. Default value is Now. evaluationGroup − This attribute determines the name of the group to be used to evaluate the chart”s expressions. The value for this attribute must match the name of the group, we would like to use as the chart”s evaluation group. hyperlinkType − This attribute can hold any text value. Default value is None. This means, neither the text fields nor the images represent hyperlinks, even if the special hyperlink expressions are present. hyperlinkTarget − This attribute helps to customize the behavior of the specified link when it is clicked in the viewer. Values could be Self, or Blank. Default value is Self. bookmarkLevel − This attribute when set to a positive integer, generates bookmarks in the reports exported to PDF. Default value is 0. customizerClass − This is the name of a class (optional) that can be used to customize the chart. The value for this element must be a String containing the name of a customizer class. Chart customization As mentioned above, JasperReports uses JFreeChart as the underlying charting library. JFreeChart contains features that are directly not supported by JasperReports. We can take advantage of these features by supplying a customizer class via the customizerClass attribute in <chart> element. A customizer class is nothing, but an implementation of the net.sf.jasperreports.engine.JRChartCustomizer interface. The easiest way to implement this interface is by extending the net.sf.jasperreports.engine.JRAbstractChartCustomizer class and thus having access to parameters, fields, and variables for more flexible chart customization based on report data. Chart Datasets One of the common properties across all chart types is <dataset> element. Chart datasets help mapping report data and retrieving chart data at runtime. Each chart type contains different sub-elements to define chart”s expressions. These expressions define the data used to generate the chart. All of these sub-elements contain a <dataset> element that defines when the chart”s expressions are evaluated and reset. Several types of chart datasets are available in JasperReports because each type of chart works with certain datasets: Pie, Category, XY, Time Series, Time Period, XYZ, and High-Low. Each of these dataset types implements net.sf.jasperreports.engine.JRChartDataset interface that define chart datasets. All chart datasets initialize and increment in the same way; however, they differ only in the type of data or data series they map. Dataset Properties Table given below summarizes the attributes of the element <dataset> − Attribute Description Values resetType This attribute determines when the value of the chart expression is to be reset. None, Report, Page, Column, Group. Default value is Report. resetGroup This attribute determines the name of the group at which the chart expression value is reset. The value for this attribute must match the name of any group declared in the JRXML report template. incrementType This attribute determines when to recalculate the value of the chart expression. None, Report, Page, Column, Group. Default value is “None”. incrementGroup This attribute determines the name of the group at which the chart expression is
JasperReports – Parameters
Reports Parameters ”; Previous Next The main input for filling a report are − report template, parameters, and data sources. This chapter will describe the parameters and in the next chapter we will discuss the data sources. Parameters are the object references, those are passed during report-filling operations to the report engine. The data which cannot be passed through the data source, can be passed by using parameters. Data like author name, title of the report, etc. can be passed through parameters. A JasperReports template or JRXML template can have zero or more parameter elements. Parameter Declaration Parameter declaration as follows − <parameter name = “exampleParameter” class = “java.lang.String” /> The Name Attribute The name attribute of the <parameter> element is mandatory. It references the parameter in report expressions by name. Parameter name should be a single word. It should not contain any special characters like dot or comma. The Class Attribute The class attribute is also mandatory and it specifies the class name for the parameter values. Its default value is java.lang.String. This can be changed to any class available at runtime. Irrespective of the type of a report parameter, the engine takes care of casting in the report expressions in which the $P{} token is used, hence making the manual casts is unnecessary. The report parameter values are always packed in a java.util.Map object, which has the parameter name as its key. Report parameters can be used in the query string of the report, so as to further customize the data set, retrieved from the database. These act like dynamic filters in the query that supplies data for the report. Built-in Parameters Following are the pre-defined report parameters, ready to use in the expressions − S.NO Parameter Name and Description 1 REPORT_PARAMETERS_MAP Contains a map with all user defined and built-in parameters. 2 REPORT_CONNECTION This points to the user supplied class java.sql.Connection, used for JDBC datasources. 3 REPORT_DATA_SOURCE This is a user supplied instance of JRDataSource representing either one of the built-in data source types or a user-defined one. 4 REPORT_MAX_COUNT This is a java.lang.Integer value, allowing the users to limit the records from datasource. 5 REPORT_SCRIPTLET This points to net.sf.jasperreports.engine.JRAbstractScriptlet and contains an instance of the report scriptlet provided by the user. 6 REPORT_LOCALE This a java.util.Locale instance, containing the resource bundle desired locale. 7 REPORT_RESOURCE_BUNDLE This points to java.util.ResourceBundle object and contains localized messages. 8 REPORT_TIME_ZONE This is a java.util.TimeZone instance, used for the date formatting. 9 REPORT_VIRTUALIZER This is an instance of net.sf.jasperreports.engine.JRVirtualizer object, and used for the page virtualization (optimize memory consumption). 10 REPORT_CLASS_LOADER This is a java.lang.ClassLoader instance to be used during the report filling process to load resources such as images, fonts, and subreport templates 11 IS_IGNORE_PAGINATION If set to java.lang.Boolean.TRUE the report will be generated on one long page and page break will not occur. Example Let us pass ReportTitle and Author to the report (generated by JasperReportFill.java). Revised file C:toolsjasperreports-5.0.1testsrccomtutorialspointJasperReportFill.java is as follows − 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(); /** * Passing ReportTitle and Author as parameters */ parameters.put(“ReportTitle”, “List of Contacts”); parameters.put(“Author”, “Prepared By Manisha”); try { JasperFillManager.fillReportToFile( sourceFileName, parameters, beanColDataSource); } catch (JRException e) { e.printStackTrace(); } } } The contents of the POJO file C:toolsjasperreports-5.0.1testsrccomtutorialspointDataBean.java are as 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; } } Let”s add parameters the <ReportTitle> and <Author> to our existing report template (Chapter Report Designs). The Report Title and Author will be displayed at the beginning of the report. 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”> <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> <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” y = “40” width = “515” height = “20”/> <textElement textAlignment = “Center”> <font size = “10”/> </textElement> <textFieldExpression class = “java.lang.String”> <![CDATA[$P{Author}]]> </textFieldExpression> </textField> </band> </title> <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>