Jasper Reports – Open Source Reporting Tool

JasperReports is an open source reporting engine. It provides 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.
  • Sub reports 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 design the JRXML file as well as textually.

3) This JRXML file is need 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 studion . 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 , 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 fields value will get repeated row by row according to the how many records that we will send from 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>

 

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="demoReport" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="bccd7b7d-02f3-464f-a375-471fa1e42b49">
	<property name="com.jaspersoft.studio.data.defaultdataadapter" value="One Empty Record"/>
	<parameter name="fontSize" class="java.lang.Integer"/>
	<queryString>
		<![CDATA[]]>
	</queryString>
	<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"/>
	<background>
		<band splitType="Stretch"/>
	</background>
	<columnHeader>
		<band height="44" splitType="Stretch">
			<staticText>
				<reportElement x="1" y="0" width="100" height="30" uuid="be117d48-bee0-4c3d-afce-cd81da251bcc"/>
				<textElement>
					<font size="18" isBold="true"/>
				</textElement>
				<text><![CDATA[id]]></text>
			</staticText>
			<staticText>
				<reportElement x="102" y="0" width="100" height="30" uuid="bdbda25a-38ef-4010-83ea-dc18fd403a4b"/>
				<textElement>
					<font size="18" isBold="true"/>
				</textElement>
				<text><![CDATA[name]]></text>
			</staticText>
			<staticText>
				<reportElement x="247" y="0" width="100" height="30" uuid="fb10bd50-e465-4047-baa8-bb08a606f0e3"/>
				<textElement>
					<font size="18" isBold="true"/>
				</textElement>
				<text><![CDATA[department]]></text>
			</staticText>
			<staticText>
				<reportElement x="449" y="0" width="100" height="30" uuid="b61d2a02-9d6e-4542-af3a-ec52dc92f03f"/>
				<textElement>
					<font size="18" isBold="true"/>
				</textElement>
				<text><![CDATA[email]]></text>
			</staticText>
		</band>
	</columnHeader>
	<detail>
		<band height="59" splitType="Stretch">
			<textField>
				<reportElement x="5" y="11" width="100" height="30" uuid="774b5b2d-0a8d-482b-b03f-dafe2f256ef1"/>
				<textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="113" y="10" width="100" height="30" uuid="1db74ec3-f783-44b9-b8b1-547cf25abc37"/>
				<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="240" y="10" width="100" height="30" uuid="0dbc3ed6-8d1f-41df-a14b-91b67e7aa7fe"/>
				<textFieldExpression><![CDATA[$F{department}]]></textFieldExpression>
			</textField>
			<textField>
				<reportElement x="430" y="10" width="100" height="30" uuid="9836e476-4267-4967-be26-6ef24b00f02d"/>
				<textFieldExpression><![CDATA[$F{email}]]></textFieldExpression>
			</textField>
		</band>
	</detail>
	<columnFooter>
		<band splitType="Stretch"/>
	</columnFooter>
</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;
	}
}

Creating 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 . Second argument is map of parameters that we have used in our report . Third argument is JRDataSource object which is basically the 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 the report as pdf file using the JasperExportManager class.

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

 

Whole program performing all the operation 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);
		
	}

}

 

Output pdf generated is given below.

Leave a Reply