Reports made easy with JasperReports

The open source JasperReports uses XML templates for your reporting needs

Generating reports is a common, if not always glamorous, task for programmers. In the past, report generation has largely been the domain of large commercial products such as Crystal Reports. Today, the open source JasperReports report generating library gives Java developers a viable alternative to commercial software.

JasperReports provides the necessary features to generate dynamic reports, including data retrieval using JDBC (Java Database Connectivity), as well as support for parameters, expressions, variables, and groups. JasperReports also includes advanced features, such as custom data sources, scriptlets, and subreports. All in all, JasperReports combines good features, maturity, community participation, and, best of all, it's free.

This article kicks off JavaWorld's new Open Source Profile column dedicated to Java-based open source tools and components. Look for upcoming articles spotlighting the Echo Web application framework and ObJectRelationalBridge, an object/relational mapping tool. Feel free to send me your suggestions for future articles.

Note: The documentation and code featured in this article are based on JasperReports version 0.3.3.

Report design

In JasperReports, you design reports using XML report templates. For example, the following XML file is a template for a report with a title, two columns of data, and page numbers:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "-//JasperReports//DTD Report Design//EN" 
 "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport name="BasicReport" >
  <parameter name="Title" class="java.lang.String"/>
  <queryString><![CDATA[select name, cost from product]]></queryString>
  <field name="NAME" class="java.lang.String"/>
  <field name="COST" class="java.lang.Double"/>
  <title>
    <band height="50">
      <textField>
        <reportElement x="0" y="0" width="200" height="50" />       
        <textFieldExpression class="java.lang.String">$P{Title}</textFieldExpression>
      </textField>
    </band>
  </title>
  <pageHeader>
    <band>
    </band>
  </pageHeader>
  <columnHeader>
    <band height="20">
      <staticText>
        <reportElement x="180" y="0" width="180" height="20"/>
        <textElement>
          <font isUnderline="true"/>
        </textElement>
        <text><![CDATA[NAME]]></text>
      </staticText>
      <staticText>
        <reportElement x="360" y="0" width="180" height="20"/>
        <textElement>
          <font isUnderline="true"/>
        </textElement>
        <text><![CDATA[COST]]></text>
      </staticText>
    </band>
  </columnHeader>
  <detail>
    <band height="20">
      <textField>
        <reportElement x="180" y="0" width="180" height="20"/>                  
        <textFieldExpression class="java.lang.String"><![CDATA[$F{NAME}]]></textFieldExpression>
      </textField>
      <textField pattern="0.00">
        <reportElement x="360" y="0" width="180" height="20"/>                  
        <textFieldExpression class="java.lang.Double"><![CDATA[$F{COST}]]></textFieldExpression>
      </textField>
    </band>
  </detail>
  <columnFooter>
    <band>
    </band>
  </columnFooter>
  <pageFooter>
    <band height="15">
      <staticText>
        <reportElement x="0" y="0" width="40" height="15"/>
        <textElement/>
        <text><![CDATA[Page:]]></text>
      </staticText>
      <textField>
        <reportElement x="40" y="0" width="100" height="15"/>
        <textElement/>
        <textFieldExpression class="java.lang.Integer"><![CDATA[$V{PAGE_NUMBER}]]></textFieldExpression>
      </textField>
    </band>
  </pageFooter>
  <summary>
    <band>
    </band>
  </summary>
</jasperReport>

The template's beginning includes any parameters passed into the report, the query that retrieves the data for the report, and the fields displayed in the report. 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 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:

<textField>
  <reportElement x="40" y="0" width="100" height="15"/>
  <textElement/>
  <textFieldExpression class="java.lang.Integer"><![CDATA[$V{PAGE_NUMBER}]]></textFieldExpression>
</textField>

The above template represents a basic, yet functional, report. A thorough JasperReports XML-template description is beyond the scope of this article, but I've included numerous links in Resources to tools that will help you edit and create your own report templates. Next, let's see how to use JasperReports in your Java applications.

Use JasperReports

To begin using JasperReports, you first must understand what objects JasperReports uses to represent the reporting process as it progresses from report design to report generation:

  • JasperDesign: Represents a report's definition. In most cases, you create a JasperDesign from an XML report template, though you can also create it programmatically.
  • JasperReport: Represents a compiled JasperDesign. The compilation process verifies the report design and compiles the design into a JasperReport object.
  • JasperPrint: Represents a generated report. You create a JasperPrint from a JasperReport through the fill process in which a report is populated with data from a data source.

The JasperReports API's flexibility lets you load JasperDesign, JasperReport, and JasperPrint objects from a file or a stream, and also lets you create these objects programmatically. You can print reports to a printer, an image, or a PDF file. The JasperReports library includes a facade class, dori.jasper.engine.JasperManager, with methods that facilitate loading, compiling, filling, and printing reports. The following code illustrates a JasperManager:

// First, load JasperDesign from XML and compile it into JasperReport
JasperDesign jasperDesign = JasperManager.loadXmlDesign("BasicReport.xml");
JasperReport jasperReport = JasperManager.compileReport(jasperDesign);
// Second, create a map of parameters to pass to the report.
Map parameters = new HashMap();
parameters.put("ReportTitle", "Basic JasperReport");
parameters.put("MaxSalary", new Double(25000.00));
// Third, get a database connection
Connection conn = Database.getConnection(); 
// Fourth, create JasperPrint using fillReport() method
JasperPrint jasperPrint = JasperManager.fillReport(jasperReport, 
   parameters, conn);
// You can use JasperPrint to create PDF
JasperManager.printReportToPdfFile(jasperPrint, "BasicReport.pdf");
// Or to view report in the JasperViewer
JasperViewer.viewReport(jasperPrint);

The code example above shows how to perform some common tasks using JasperReports. In a real-world application, you'd find it impractical to load and compile the JasperDesign every time you wanted to generate a report. Since report designs are largely static, in most cases, you'd precompile your JasperDesign files to increase speed. You can also increase a large report's speed by generating and saving JasperPrint objects as part of a nightly batch process.

That's all you need to get started; download JasperReports and you'll be up and running in no time.

Reports the easy way

In this article, you learned how the open source JasperReports can aid your Java reporting needs. If you are building a reporting application or looking to add reporting capability to an existing application, look at JasperReports. Visit the JasperReports homepage for more information and download the latest version.

Erik Swenson is a consultant and the founder of Open Source Software Solutions. Swenson specializes in Java development using open source software and components. He developed the JasperEdit and OpenReports open source projects.

Learn more about this topic

  • Open source alternatives to JasperReports include:

Join the discussion
Be the first to comment on this article. Our Commenting Policies