Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

JasperReports – Open Source Reporting Tool

DZone's Guide to

JasperReports – Open Source Reporting Tool

Check out this complete tutorial on how to create and use JasperReports to provide document reporting capabilities.

· Open Source Zone ·
Free Resource

Are you looking for ways to manage your open source risk? We can help. Learn more.

JasperReports is an open source reporting engine. It provides the ability to deliver rich content onto to the printer, the screen, or into various formats such as  PDF, HTML, XLS, RTF, ODT, CSV, TXT and XML files. It is a Java library and can be used in a variety of Java-enabled applications to generate dynamic content. Its main purpose is to help create page-oriented, ready-to-print documents in a simple and flexible manner. JasperReports can also be used to provide reporting capabilities in our applications.

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.

Features of JasperReports :

  • Flexible report layout.
  • Data can be presented either textually or graphically.
  • Developers can supply data in multiple ways.
  • Multiple data sources can be used to transfer data.
  • Watermarks can also be applied.
  • Subreports can also be generated.
  • Various formats of reports can be exported. 

Maven Dependency :

<dependency>    
  <groupId>net.sf.jasperreports</groupId>
  <artifactId>jasperreports</artifactId>     
  <version>6.1.0</version> 
</dependency>

 

Working Process: 

1) Add Jasper Library to the project.

2) Create some layout design before start reporting from Java code. Jasper's reporting layout design is nothing but an XML file with the extension .jrxml. JasperStudio or iReport as GUI tools can be used to visually as well as textually design the JRXML file.

3) This JRXML file needs to be compiled to generate .jasper. JRXML file can be compiled on the fly, dynamically from our Java code. We can also use iReport or JasperStudio to compile the .jrxml file to create a Jasper file.

4) Once compiled and .jasper are created, we can start feeding data into the report from the Java code.

Tools that can be used to generate .jrxml files: 

  1. Eclipse plugin for Jaspersoft studio
  2. iReport
  3. Jaspersoft Studio

Report Template

A .jrxml report template is consist of the following parts shown in the below figure.

 

Designing a Report 

We are going to create a simple Jasper report design i.e., .jrxml file through Jaspersoft Studio.

You need to install the Jaspersoft Studio. After installation you need to follow these steps:

Step 1

Go to  File > New > others > Jaspersoft Studio > JasperReports project  

Now enter the name of the project and press enter . Your created project will now be visible into the project explorer.

Step 2

Select your created project name and right click then New > Jasper Report > Blank A4 (For practice ) > Next > enter the name of .jrxml > Next  > Next > Finish

Your sample report design will be generated now with all the report design parts as shown in the below figure.

You can also switch to source view to see the ..jrxml code of the default generated code of the report design. Below is the ..jrxml code.

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.4.0.final using JasperReports Library version 6.4.1  -->
<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="Blank_A4" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="a51bd162-94c0-42cc-8eea-ccac0f4dc317">
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
<queryString>
<![CDATA[]]>
</queryString>
<background>
<band splitType="Stretch"/>
</background>
<title>
<band height="79" splitType="Stretch"/>
</title>
<pageHeader>
<band height="35" splitType="Stretch"/>
</pageHeader>
<columnHeader>
<band height="61" splitType="Stretch"/>
</columnHeader>
<detail>
<band height="125" splitType="Stretch"/>
</detail>
<columnFooter>
<band height="45" splitType="Stretch"/>
</columnFooter>
<pageFooter>
<band height="54" splitType="Stretch"/>
</pageFooter>
<summary>
<band height="42" splitType="Stretch"/>
</summary>
</jasperReport>

 

Now you can change this report design from source view by manually writing the ..jrxml code or you can switch to the design view, where you can drag and drop the components from the Pallet view present at the right side .

In this case, we are manually writing the ..jrxml code. In this report design, we are taking four string fields as id, name, department, and email.

<field name="id" class="java.lang.String"/>
<field name="name" class="java.lang.String"/>
<field name="department" class="java.lang.String"/>
<field name="email" class="java.lang.String"/>

We will now define the field header for all the four fields in the page header part of the .jrxml report.

<pageHeader>
        <band height="30" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0" width="69" height="24" uuid="012424cf-712d-4e84-9906-776e1850b85a"/>
                <textElement verticalAlignment="Bottom">
                    <font size="10" isBold="false"/>
                </textElement>
                <text><![CDATA[ID]]></text>
            </staticText>
            <staticText>
                <reportElement x="140" y="0" width="94" height="24" uuid="724d23ca-6ad1-4be5-bae1-77c07dd31ba0"/>
                <textElement textAlignment="Center"/>
                <text><![CDATA[Name]]></text>
            </staticText>
            <staticText>
                <reportElement x="280" y="0" width="69" height="24" uuid="1e85a3f6-ba9d-47a7-8f25-cf37f5b4448d"/>
                <text><![CDATA[Department]]></text>
            </staticText>
            <staticText>
                <reportElement x="420" y="0" width="108" height="24" uuid="044a8958-4960-4fa3-9cd6-c594595c521a"/>
                <text><![CDATA[Email]]></text>
            </staticText>
        </band>
    </pageHeader>

Now we will use the above-declared fields in the detail part of the .jrxml report because this field's value will get repeated row by row according to the how many records that we will send from the Java code.

<detail>
        <band height="30" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="69" height="24" uuid="d844cada-1aa4-4208-9fc1-dcdf62a72235"/>
                <textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="140" y="0" width="94" height="24" uuid="14399970-e399-41e0-b6f9-1218079fd56c"/>
                <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="280" y="0" width="69" height="24" uuid="b5b0fe03-9b8f-48c6-ba51-c218427028f6"/>
                <textFieldExpression><![CDATA[$F{department}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="420" y="0" width="108" height="24" uuid="c3094477-bb5e-4d5c-a440-8d7c7f2a1d3e"/>
                <textFieldExpression><![CDATA[$F{email}]]></textFieldExpression>
            </textField>
        </band>
    </detail>

 

The final .jrxml file "demoReport.jrxml" is given below :

<?xml version="1.0" encoding="UTF-8"?>
<!-- Created with Jaspersoft Studio version 6.4.0.final using JasperReports Library version 6.4.1  -->
<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="Blank_A4" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="a51bd162-94c0-42cc-8eea-ccac0f4dc317">
<property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
<queryString>
<![CDATA[]]>
</queryString>
<background>
<band splitType="Stretch"/>
</background>
<title>
<band height="79" splitType="Stretch"/>
</title>
<pageHeader>
<band height="35" splitType="Stretch"/>
</pageHeader>
<columnHeader>
<band height="61" splitType="Stretch"/>
</columnHeader>
<detail>
<band height="125" splitType="Stretch"/>
</detail>
<columnFooter>
<band height="45" splitType="Stretch"/>
</columnFooter>
<pageFooter>
<band height="54" splitType="Stretch"/>
</pageFooter>
<summary>
<band height="42" splitType="Stretch"/>
</summary>
</jasperReport>

 

The Design version of the above-generated sample report is given below. You can check that design view by clicking the design view option in Jaspersoft Studio.

The Preview of the demo report that is generated above is given below. You can check the preview in the Jaspersoft Studio by clicking the preview button.

Compiling the Jasper Report

We will now compile the report design i.e .jrxml file . After compilation a .jasper file will be generated . For compilation we will use JasperCompileManager class and we will use its static method compileReportToFile to compile the .jrxml report . During compilation if report design is not a valid design a JRException will occur.

String sourceFileName = "D://demoReport.jrxml";
try {
      //Compiling the jrxml  
      JasperCompileManager.compileReportToFile(sourceFileName);
 } catch (JRException e) {
      e.printStackTrace();
 }

 Below is the given program to compile the .jrxml report and generate a jasper file. After compilation "demoReport.jasper" file will get generated.

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;

public class JasperReportCompilationExample {
   public static void main(String[] args) {
      String sourceFileName = "D://demoReport.jrxml";
      System.out.println("Compiling Report Design ...");
      try {
       JasperReport jasperReport =  JasperCompileManager.compileReportToFile(sourceFileName);
      } catch (JRException e) {
         e.printStackTrace();
      }
      System.out.println("Compilation Done!!! ...");
   }
}


Creating the EmployeeRecordModel class with the four fields of type string that is declared in the demoReport.

public class EmployeeRecordModel {

private String id;
private String name;
private String department;
private String email;

public EmployeeRecordModel(String id, String name , String department , String email){
this.id = id;
this.name = name;
this.department = department;
this.email = email;
}
        public String getId() {
return id;
}
        public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getDepartment() {
return department;
}

public void setDepartment(String department) {
this.department = department;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}
}

Create a JRDataSource  object by passing the list of EmployeeRecordModel object in the argument.

List<EmployeeRecordModel> modelList = new ArrayList<EmployeeRecordModel>();
modelList.add(new EmployeeRecordModel("1","Akshay","IT","akshaysharma@gmail.com"));
modelList.add(new EmployeeRecordModel("2","Rahul","IT","rahulgupta@gmail.com")); 
modelList.add(new EmployeeRecordModel("3","Dev","IT","dev@gmail.com")); 
modelList.add(new EmployeeRecordModel("4","Ankit","IT","ankit@gmail.com")); 
JRBeanCollectionDataSource dataSource  = new JRBeanCollectionDataSource(modelList);

 

Generating the Jasper Print Object

Now generating the JasperPrint object from the compile report i.e .jasper file by calling the static fillReport method of JasperFillManager class . This method accepts three arguments .

public static JasperPrint fillReport(
JasperReport jasperReport, 
Map<String,Object> parameters, 
JRDataSource dataSource
);

Where , first argument is the jasperReport object. The second argument is a map of parameters that we have used in our report. The third argument is JRDataSource object which is basically the data source of the list of records having the fields that is used in the report.

JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, dataSource);

Now, exporting the report as .pdf file using the JasperExportManager class.

String path = "D://demoReportOutput.pdf";
JasperExportManager.exportReportToPdfFile(jasperPrint,path);

 

The whole program performing all the operations is given below.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;


public class JasperPractice {

public static void main(String[] args) throws JRException {
String sourceFileName = "D://demoReport.jrxml";
JasperReport jasperReport = null;

    jasperReport = JasperCompileManager.compileReport(sourceFileName);


List<EmployeeRecordModel> modelList = new ArrayList<EmployeeRecordModel>();
modelList.add(new EmployeeRecordModel("1","Akshay","IT","akshaysharma@gmail.com"));
modelList.add(new EmployeeRecordModel("2","Rahul","IT","rahulgupta@gmail.com")); 
modelList.add(new EmployeeRecordModel("3","Dev","IT","dev@gmail.com")); 
modelList.add(new EmployeeRecordModel("4","Ankit","IT","ankit@gmail.com")); 

JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(modelList);

Map<String,Object> params = new HashMap<String,Object>();
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, dataSource);

String path = "D://demoReportOutput.pdf";
JasperExportManager.exportReportToPdfFile(jasperPrint,path);

}

}

 

The output .pdf generated is given below.

Software composition Analysis for DevSecOps. Start finding vulnerabilities in your open source components today.

Topics:
java ,j2ee ,java application ,reports ,java library ,jasperreports ,open source

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}