Starting with JasperReports javacode 9085791

Starting with JasperReports

My first days at AMIS I examined JasperReports (v. 0.6.3), an open source report-generating library. This tool is entirely written in Java and uses XML report templates to generate reports you can display on the screen, send to a printer, or save as a PDF document.

In order to fill a report with data, the report design (template) must be compiled first.
This compilation is performed by the compileReport() method exposed by the net.sf.jasperreports.engine.JasperCompileManager class.
Through compilation, the report design is loaded into a report design object that is then serialized and stored on disk (net.sf.jasperreports.engine.JasperReport). This serialized object is then used when the application wants to fill the specified report design with data. In fact, the compilation of a report design implies the compilation of all Java expressions defined in the XML file representing the report design. Various verifications are made at compilation time, to check the report design consistency. The result is a ready to fill report design that will be then used to generate documents on different sets of data.

In order to fill a report design, one can use the fillReport() method exposed by the net.sf.jasperreports.engine.JasperFillManager class. This method takes as parameters:

  • the report design object, or a file representing the specified report design object, in a serialized form
  • a map of reportparameters
  • a JDBC connection to the database from where to retrieve the data to fill the report

The result is an object that represents the ready to print document (net.sf.jasperreports.engine.JasperPrint) and can be stored onto the disk, in a serialized form, for later use, or can be delivered to the printer, to the screen or can be transformed into a PDF, HTML, XLS, CSV or XML document.
I’ve only tried the PDF transformation. The following code illustrates this:

package nl.amis.jasper.test;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.view.JasperViewer;
import nl.amis.database.Database;

public class EmpDeptReport {

        public static void main(String[] args) {
//                 First, load JasperDesign from XML and compile it into JasperReport
                try {
                        JasperDesign jasperDesign = JRXmlLoader.load("EmpDeptReport.xml");
                        JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

//                 Second, create a map of parameters to pass to the report.
                        Map parameters = new HashMap();
                        parameters.put("Title", "EmpDept JasperReport");

//                 Third, get a database connection
                         Connection conn = Database.getConnection();

//                 Fourth, create JasperPrint using fillReport() method
                        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport,
                                           parameters, conn);

//                 You can use JasperPrint to create PDF
                        JasperExportManager.exportReportToPdfFile(jasperPrint, "EmpDeptReport.pdf");

//                 Or to view report in the JasperViewer
                        JasperViewer.viewReport(jasperPrint);
                } catch (JRException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                }
        }
}

To create a XML report template I’ve used OpenReports Designer (v. 1.10).
This is a tool that combines a visual report designer, an XML report definition editor, and report viewer into one interface to provide a complete integrated report development environment.

Starting with JasperReports OpenReports 1 10

The XML file EmpDeptReport.xml – which can be downloaded below – is a template for a report which retrieves data from Oracle’s Emp and Dept tables.
In the following I’ll explain the structure of this template. This structure is declared in a DTD file supplied with the JasperReports engine.

Every JasperReports XML template starts with with the following structure:

< ?xml version="1.0" encoding="UTF-8"?>
< !DOCTYPE jasperReport PUBLIC "-//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
< jasperReport name="EmpDeptReport" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="30" bottomMargin="30">

< /jasperReport>

Parameters are object references that are passed-in to the report filling operations (see EmpDeptReport class above).
Declaring a parameter in a report design is very simple and it requires specifying only its name and its class:

< parameter name=”Title” class=”java.lang.String”>
< /parameter>

When using a JDBC data source, one could pass a Connection object to the report filling operations (see also EmpDeptReport class) and specify the query in the report definition itself:

< queryString> < ![CDATA[select e.empno
                                       , e.ename
                                       , e.job
                                       , e.mgr
                                       , to_char(e.hiredate, 'dd-mm-yyyy') hiredate
                                       , e.sal
                                       , e.comm
                                       , e.deptno
                                       , d.dname
                                       , d.loc
                                  from emp e
                                  ,    dept d
                                  where e.deptno = d.deptno
                                  order by e.deptno]]> < /queryString>

Report fields represent the only way to map data from the data source into the report generating routines.
We can define the following field in our report design:

< field name="ENAME" class="java.lang.String">
< /field>

Expressions are a powerful feature of JasperReports. They can be used for declaring report variables that perform various calculations, for data grouping on the report, to specify report text fields content or to further customize the appearance of objects on the report.
Basically, all report expressions are Java expressions that can reference report fields and report variables.
In an XML report design there are several elements that define expressions: < variableExpression> , < initialValueExpression> , < groupExpression> , < printWhenExpression> , < imageExpression> and < textFieldExpression> .
In order to use a report field reference in an expression, the name of the field must be put between $F{ and } character sequences.

A Report variable is a special objects build on top of an expression. Variables can be used to simplify the report design by declaring only once an expression that is heavily used throughout the report design or to perform various calculations on the corresponding expressions.
Variables can perform built-in types of calculations on their corresponding expression values like: count, sum, average, lowest, highest, variance, etc.

A variable that performs the sum of the SAL field per department should be declared like this:

< variable name="SalSumDept" class="java.math.BigDecimal" resetType="Group" resetGroup="DeptGroup" calculation="Sum">
                < variableExpression> < ![CDATA[$F{SAL}]]> < /variableExpression>
< /variable>

As you can see a group DeptGroup is introduced.
Groups represent a flexible way to organize data on a report. When filling a report, the JasperReports engine test all the defined group expressions to see whether a group rupture has occurred and if so it introduces the corresponding < groupFooter> and < groupHeader> sections on the report:

< group name="DeptGroup">
        < groupExpression> < ![CDATA[$F{DEPTNO}]]> < /groupExpression>
        < groupHeader>

        < /groupHeader>
        < groupFooter>

        < /groupFooter>
< /group>

By the the way, I didn’t succeed in creating groupHeaders and groupFooters with OpenReports Designer (v. 1.10), so I did some copy-paste from another template.

The template’s remainder divides into six report sections:

  • title
  • pageHeader
  • columnHeader
  • detail
  • columnFooter
  • pageFooter
  • summary

Each report section, called a band, is given a height. Each band can include multiple staticText and textField elements, which are given a position, size, and value. Report parameters, fields, and variables are referenced using P${name}, F${name}, and V${name}, respectively.

For example, the following lines in the page footer section create a staticText and a textField containing the current page number. The page number’s value is set to the variable PAGE_NUMBER, defined internally by JasperReports and available to all reports:

< pageFooter>
        < band height="15">
                < staticText>
                        < reportElement positionType="Float" x="0" y="0" width="40"
                         height="15"/>
                        < textElement/>
                        < text> < ![CDATA[Page:]]> < /text>
                < /staticText>
                < textField>
                        < reportElement positionType="Float" x="40" y="0" width="100"
                          height="15"/>
                        < textElement/>
                        < textFieldExpression="java.lang.Integer"> < ![CDATA[$V{PAGE_NUMBER}]]
                  >
                        < /textFieldExpression>
                < /textField>
        < /band>
< /pageFooter>

Starting with JasperReports JasperReport

Resources:
‘Reports made easy with JasperReports’ by Erik Swenson:
http://www.javaworld.com/javaworld/jw-09-2002/jw-0920-opensourceprofile.html

Find the JasperReports homepage at:
http://jasperreports.sourceforge.net

OpenReports Project:
http://opensourcesoft.net

Report design tools for Eclipse:
http://sourceforge.net/projects/jeez (this plugin doesn’t seem to work with Eclipse 3.0.1)

Downloads:
EmpDeptReport.java
Database.java
EmpDeptReport.xml

81 Comments

  1. Uzay February 7, 2012
  2. Pingback: Jessie March 27, 2008
  3. Eko SW August 23, 2007
  4. chetan April 12, 2007
  5. Victor Ott January 16, 2007
  6. Ashok December 15, 2006
  7. shohan October 19, 2006
  8. shohan October 14, 2006
  9. suresh October 7, 2006
  10. sherkspear October 4, 2006
  11. Manikandan.J September 15, 2006
  12. Utsav September 15, 2006
  13. Alok Saha September 13, 2006
  14. Allan August 6, 2006
  15. Delia Montoya Casas June 16, 2006
  16. peacemaker June 15, 2006
  17. sri May 29, 2006
  18. bum May 29, 2006
  19. ehimare May 17, 2006
  20. Gopikrishna April 21, 2006
  21. Luiz Mendes Almeida April 17, 2006
  22. Ravi April 4, 2006
  23. Yanai March 15, 2006
  24. Aditya March 11, 2006
  25. Paul March 7, 2006
  26. naga srikanth February 6, 2006
  27. hema January 19, 2006
  28. Jay January 6, 2006
  29. Can January 5, 2006
  30. ikuyuldar December 27, 2005
  31. Ragunatha Reddy Kummetha December 16, 2005
  32. jaya December 14, 2005
  33. Artis December 9, 2005
  34. nasch December 7, 2005
  35. Baziek November 30, 2005
  36. soumak November 17, 2005
  37. forever_young October 25, 2005
  38. inbaselvan October 6, 2005
  39. inbaselvan October 6, 2005
  40. nits September 16, 2005
  41. HENRY September 1, 2005
  42. Milind August 22, 2005
  43. kRESTAURANT August 17, 2005
  44. GoodBoy August 16, 2005
  45. netanel August 1, 2005
  46. beginner July 26, 2005
  47. nicos July 12, 2005
  48. anil kumar June 15, 2005
  49. elle June 9, 2005
  50. vijaya June 9, 2005
  51. sai June 2, 2005
  52. geoff May 27, 2005
  53. vijaya May 27, 2005
  54. Ouethy May 25, 2005
  55. Jeremie May 25, 2005
  56. David May 9, 2005
  57. bugs April 27, 2005
  58. Cubus April 26, 2005
  59. nathaly April 19, 2005
  60. lavanya April 19, 2005
  61. Anjali April 19, 2005
  62. Anjali April 19, 2005
  63. Anjali April 19, 2005
  64. Anjali April 19, 2005
  65. Anjali April 19, 2005
  66. JavaGuy April 15, 2005
  67. Jasper April 14, 2005
  68. John Tharakan April 14, 2005
  69. Beginner April 8, 2005
  70. Mitz April 6, 2005
  71. jasferdz April 2, 2005
  72. Gregory Beumer April 1, 2005
  73. michael March 31, 2005
  74. Lucas Jellema March 28, 2005
  75. Beginner March 24, 2005
  76. TERMination March 8, 2005
  77. Arun March 3, 2005
  78. dell February 16, 2005
  79. dell February 16, 2005
  80. Jasper January 31, 2005
  81. Raghu January 31, 2005
  82. Lucas January 21, 2005
  83. Pingback: cat /dev/random » Links January 20, 2005