refermycode.com

Develop your world..

Export the multisheet excel file by using Jasper.

In this blog we are going to learn, how to export multisheet excel file by using Jasper. So we will take an example in which we will print some information in one sheet and some information in another sheet.

Employee NumberEmployee NameEmployee AddressEmployee Salary
1001Adams Springfield 40,000
1002Anderson Clinton 50,000
1003Clark Madison 50,000
1004David Washington 60,000
1005Harris Clinton 50,000
1006Johnson Franklin 60,000
1007Mitchell Washington 50,000
1008Nelson Chester 30,000
1009Robinson Marion 60,000
1010Roberts Greenville 70,000
1011Smith Georgetown 80,000
1012Scott Salem 40,000

In another sheet we will display the information of Department.

Department NumberDepartment NameLocation
101HR Madison
102IT Madison
103Payroll Madison
104Inventory Washington
105Production Washington

We have print this records into 2 different sheets of single excel file.

So let us start with the designing phase,

In iReport we are going to create 2 different design (Sub Reports) for both sheets, one for Employee Information and another for Department Information. Hence we are merging these 2 Sub Report into another report which we are calling here Main Report.

Step 1: Design of First Sub Report.

We need to add the fields which is required to display the information about Employees. Hence we are going to add the necessary field into the Column Header and Detail section as shown in following screenshot.

Blog4_1

Here is the sample code of First Subreport.

<?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="mayursreport" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<property name="ireport.zoom" value="1.464100000000001"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<field name="employeeNumber" class="java.lang.String"/>
<field name="employeeName" class="java.lang.String"/>
<field name="employeeAddress" class="java.lang.String"/>
<field name="employeeSalary" class="java.lang.String"/>
<pageHeader>
<band height="50">
<staticText>
        <reportElement x="120" y="16" width="300" height="20"/>
        <textElement textAlignment="Center">
                <font size="12" isBold="true"/>
        </textElement>
        <text><![CDATA[This is First SubReport Title!]]></text>
</staticText>
</band>
</pageHeader>
<columnHeader>
<band height="30">
<staticText>
        <reportElement x="17" y="5" width="120" height="20"/>
        <textElement>
                <font size="8" isBold="true"/>
        </textElement>
        <text><![CDATA[Employee Number]]></text>
</staticText>
<staticText>
        <reportElement x="150" y="5" width="120" height="20"/>
        <textElement>
                <font size="8" isBold="true"/>
        </textElement>
        <text><![CDATA[Employee Name]]></text>
</staticText>
<staticText>
        <reportElement x="283" y="5" width="120" height="20"/>
        <textElement>
                <font size="8" isBold="true"/>
        </textElement>
        <text><![CDATA[Employee Address]]></text>
</staticText>
<staticText>
        <reportElement x="420" y="5" width="120" height="20"/>
        <textElement>
                <font size="8" isBold="true"/>
        </textElement>
        <text><![CDATA[Employee Salary]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="26">
<textField>
        <reportElement x="17" y="5" width="120" height="20"/>
        <textElement>
                <font size="8"/>
        </textElement>
        <textFieldExpression><![CDATA[$F{employeeNumber}]]></textFieldExpression>
</textField>
<textField>
        <reportElement x="150" y="5" width="120" height="20"/>
        <textElement>
                <font size="8"/>
        </textElement>
        <textFieldExpression><![CDATA[$F{employeeName}]]></textFieldExpression>
</textField>
<textField>
        <reportElement x="283" y="5" width="120" height="20"/>
        <textElement>
                <font size="8"/>
        </textElement>
        <textFieldExpression><![CDATA[$F{employeeAddress}]]></textFieldExpression>
</textField>
<textField>
        <reportElement x="420" y="5" width="120" height="20"/>
        <textElement>
                <font size="8"/>
        </textElement>
        <textFieldExpression><![CDATA[$F{employeeSalary}]]></textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>

Step 2: Design of Second Sub Report.

In this step we will add the fields which is required to display the information about Department. Hence we are going to add the necessary field into the Column Header and Detail section as shown in following screenshot.

Blog4_2

Here is the sample code of Second Subreport.

<?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="mayursreport" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<property name="ireport.zoom" value="1.464100000000001"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<field name="departmentNumber" class="java.lang.String"/>
<field name="departmentName" class="java.lang.String"/>
<field name="departmentLocation" class="java.lang.String"/>
<pageHeader>
<band height="50">
<staticText>
        <reportElement x="114" y="20" width="300" height="20"/>
        <textElement textAlignment="Center">
                <font size="12" isBold="true"/>
        </textElement>
        <text><![CDATA[This is Second SubReport Title!]]></text>
</staticText>
</band>
</pageHeader>
<columnHeader>
<band height="30">
<staticText>
        <reportElement x="17" y="5" width="120" height="20"/>
        <textElement>
                <font size="8" isBold="true"/>
        </textElement>
        <text><![CDATA[Department Number]]></text>
</staticText>
<staticText>
        <reportElement x="150" y="5" width="120" height="20"/>
        <textElement>
                <font size="8" isBold="true"/>
        </textElement>
        <text><![CDATA[Department Name]]></text>
</staticText>
<staticText>
        <reportElement x="283" y="5" width="120" height="20"/>
        <textElement>
                <font size="8" isBold="true"/>
        </textElement>
        <text><![CDATA[Location]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="26">
<textField>
        <reportElement x="17" y="5" width="120" height="20"/>
        <textElement>
                <font size="8"/>
        </textElement>
        <textFieldExpression><![CDATA[$F{departmentNumber}]]></textFieldExpression>
</textField>
<textField>
        <reportElement x="150" y="5" width="120" height="20"/>
        <textElement>
                <font size="8"/>
        </textElement>
        <textFieldExpression><![CDATA[$F{departmentName}]]></textFieldExpression>
</textField>
<textField>
        <reportElement x="283" y="5" width="120" height="20"/>
        <textElement>
                <font size="8"/>
        </textElement>
        <textFieldExpression><![CDATA[$F{departmentLocation}]]></textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>

Step 3: Design of Main Report.

In this step we are going to add this two subreports into our main report. To Separate these two reports we are going to use page break tool which is provided by iReport tool. So add first subreport in fist detail band, then page break in second detail band and finally second subreport in third detail band as shown in following screenshot.

Blog4_3

Here is the sample code of Main Report.

<?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="mayursreport" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<parameter name="SUBREPORT_1" class="net.sf.jasperreports.engine.JasperReport"/>
<parameter name="SUBREPORT_2" class="net.sf.jasperreports.engine.JasperReport"/>
<parameter name="SUBREPORT_DATA_1" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
<parameter name="SUBREPORT_DATA_2" class="net.sf.jasperreports.engine.data.JRBeanCollectionDataSource"/>
<detail>
<band height="26">
<subreport>
        <reportElement mode="Transparent" x="0" y="0" width="555" height="26"/>
        <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource ($P{SUBREPORT_DATA_1}.getData())]]></dataSourceExpression>
        <subreportExpression class="net.sf.jasperreports.engine.JasperReport"><![CDATA[$P{SUBREPORT_1}]]></subreportExpression>
</subreport>
</band>
<band height="13">
<break>
        <reportElement mode="Opaque" x="0" y="6" width="555" height="1"/>
</break>
</band>
<band height="27">
<subreport>
        <reportElement mode="Transparent" x="0" y="0" width="555" height="26"/>
        <dataSourceExpression><![CDATA[new net.sf.jasperreports.engine.data.JRBeanCollectionDataSource ($P{SUBREPORT_DATA_2}.getData())]]></dataSourceExpression>
        <subreportExpression class="net.sf.jasperreports.engine.JasperReport"><![CDATA[$P{SUBREPORT_2}]]></subreportExpression>
</subreport>
</band>
</detail>
</jasperReport>

In this way, we have finished design phase, now let us move to the Java Code.

We need to create two separate POJO classes to store the information for Employee and Department, hence we have created distinct classes for Employee and Department in same package.

Here is sample code for Employee class.

package com.refermycode.mypackage;
/*
* @author Mayur
*/

public class Employee {
String employeeNumber = "";
String employeeName = "";
String employeeAddress = "";
String employeeSalary = "";
public String getEmployeeAddress() {
return employeeAddress;
}
public void setEmployeeAddress(String employeeAddress) {
this.employeeAddress = employeeAddress;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(String employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getEmployeeSalary() {
return employeeSalary;
}
public void setEmployeeSalary(String employeeSalary) {
this.employeeSalary = employeeSalary;
}
}

Here is sample code for Department.

package com.refermycode.mypackage;

/*
* @author Maddy
*/

public class Department {
String departmentNumber = "";
String departmentName = "";
String departmentLocation = "";
public String getDepartmentNumber() {
return departmentNumber;
}
public void setDepartmentNumber(String departmentNumber) {
this.departmentNumber = departmentNumber;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
public String getDepartmentLocation() {
return departmentLocation;
}
public void setDepartmentLocation(String departmentLocation) {
this.departmentLocation = departmentLocation;
}
}

Now let us write a another class which we will use to store the data and export it into the Excel file.

Here is sample code for JasperBlog4.java which include the main method in it.

package com.refermycode.mypackage;

import java.io.*;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

/*
* @author Mayur
*/

public class JasperBlog4 {

/* Method to add Employee Information */
public static List addEmployeeInfo() {
List employeeList = new ArrayList();

Employee employee = new Employee();
employee.setEmployeeNumber("1001");
employee.setEmployeeName("Adams");
employee.setEmployeeAddress("Springfield");
employee.setEmployeeSalary("40,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1002");
employee.setEmployeeName("Anderson");
employee.setEmployeeAddress("Clinton");
employee.setEmployeeSalary("50,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1004");
employee.setEmployeeName("Clark");
employee.setEmployeeAddress("Madison");
employee.setEmployeeSalary("50,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1004");
employee.setEmployeeName("David");
employee.setEmployeeAddress("Washington");
employee.setEmployeeSalary("60,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1005");
employee.setEmployeeName("Harris");
employee.setEmployeeAddress("Clinton");
employee.setEmployeeSalary("50,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1006");
employee.setEmployeeName("Johnson");
employee.setEmployeeAddress("Franklin");
employee.setEmployeeSalary("60,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1007");
employee.setEmployeeName("Mitchell");
employee.setEmployeeAddress("Washington");
employee.setEmployeeSalary("50,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1008");
employee.setEmployeeName("Nelson");
employee.setEmployeeAddress("Chester");
employee.setEmployeeSalary("30,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1009");
employee.setEmployeeName("Robinson");
employee.setEmployeeAddress("Marion");
employee.setEmployeeSalary("60,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1010");
employee.setEmployeeName("Roberts");
employee.setEmployeeAddress("Greenville");
employee.setEmployeeSalary("70,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1011");
employee.setEmployeeName("Smith");
employee.setEmployeeAddress("Georgetown");
employee.setEmployeeSalary("80,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1012");
employee.setEmployeeName("Scott");
employee.setEmployeeAddress("Salem");
employee.setEmployeeSalary("40,000");
employeeList.add(employee);

return employeeList;
}

/* Method to add Department Information */
public static List addDepartmentInfo() {
List departmentList = new ArrayList();

Department department = new Department();
department.setDepartmentNumber("101");
department.setDepartmentName("HR");
department.setDepartmentLocation("Madison");
departmentList.add(department);

department = new Department();
department.setDepartmentNumber("102");
department.setDepartmentName("IT");
department.setDepartmentLocation("Madison");
departmentList.add(department);

department = new Department();
department.setDepartmentNumber("103");
department.setDepartmentName("Payroll");
department.setDepartmentLocation("Madison");
departmentList.add(department);

department = new Department();
department.setDepartmentNumber("104");
department.setDepartmentName("Inventory");
department.setDepartmentLocation("Washington");
departmentList.add(department);

department = new Department();
department.setDepartmentNumber("105");
department.setDepartmentName("Production");
department.setDepartmentLocation("Washington");
departmentList.add(department);

return departmentList;
}

public static void main(String[] args) throws FileNotFoundException, IOException {
try {
/* Hashmap to store all Parameters required for Export Operation */
HashMap parameters = new HashMap();

/* Loading and Compiling First Subreport */
InputStream inputStreamSubReport1 = new FileInputStream("C:/JasperBlog4/src/com/refermycode/mypackage/SubReport1.jrxml");
JasperDesign jasperDesignSubReport1 = JRXmlLoader.load(inputStreamSubReport1);
JasperReport jasperReportSubReport1 = JasperCompileManager.compileReport(jasperDesignSubReport1);

/* Loading and Compiling Second Subreport */
InputStream inputStreamSubReport2 = new FileInputStream("C:/JasperBlog4/src/com/refermycode/mypackage/SubReport2.jrxml");
JasperDesign jasperDesignSubReport2 = JRXmlLoader.load(inputStreamSubReport2);
JasperReport jasperReportSubReport2 = JasperCompileManager.compileReport(jasperDesignSubReport2);

/* Loading and Compiling Main Report */
InputStream inputStream = new FileInputStream("C:/JasperBlog4/src/com/refermycode/mypackage/MainReport.jrxml");
JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

List employeeList = addEmployeeInfo();
List departmentList = addDepartmentInfo();

/* Putting the Subreport and Data into Parameters */
parameters.put("SUBREPORT_1", jasperReportSubReport1);
parameters.put("SUBREPORT_2", jasperReportSubReport2);
parameters.put("SUBREPORT_DATA_1", new JRBeanCollectionDataSource(employeeList));
parameters.put("SUBREPORT_DATA_2", new JRBeanCollectionDataSource(departmentList));

/* Putting some Dummy Data for Main Report,
* if you not pass this dummy data then result will be blank sheet.
* and if you send multiple times then it will print same data multiple times.*/

ArrayList mainReportsList = new ArrayList&lt;&gt;();
mainReportsList.add("DummyValue");

JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(mainReportsList);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);

/*If you want to print the data in PDF format then you can add this line into code.
JasperExportManager.exportReportToPdfFile(jasperPrint, "C:/test_jasper.pdf");
*/

ByteArrayOutputStream outputByteArray = new ByteArrayOutputStream();
OutputStream outputfile = new FileOutputStream(new File("C:/test_jasper.xls"));

JRXlsExporter xlsExporter = new JRXlsExporter();
xlsExporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
xlsExporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, outputByteArray);

/* This is Properties of Excel file which is used for configuration setting. */
xlsExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
xlsExporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
xlsExporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.FALSE);
xlsExporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);

xlsExporter.exportReport();
outputfile.write(outputByteArray.toByteArray());

} catch (JRException ex) {
Logger.getLogger(JasperBlog4.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

To export this file we need additional library called as poi-X.X.jar  which can be found in following path of installation folder of iReport.

“iReport-X.X.X\ireport\modules\ext”.

Include this into classpath of project. If you forget to include this library in Project then it will throw following exception while execution of Project.

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/poi/ss/usermodel/RichTextString

If you have follow all the above steps then run your project and you will get following excel sheet with two sheets as shown in following screenshot.

Blog4_4

In short when we need to display our data on multiple sheets then we need to add below 2 things into ireport design.

  1. Page Break Component to create multiple pages.
  2. Set following property “net.sf.jasperreports.export.xls.one.page.per.sheet” to TRUE.

In this way we can export the multisheet excel file by using Jasper.

Please don’t forget to comment your feedback for this post. 🙂

Add new font in Jasper Reports Font Library.

In this blog we are going to add new font in Jasper Font Library to remove font dependency. Hope you have read my previous blog on Remove font dependency from Jasper Report Font Library. As discussed in previous blog if we are using any font which is not present in our Jasper Report Font Library then it will raised following exception while export phase,

net.sf.jasperreports.engine.util.JRFontNotFoundException:
Font ‘Font_Name’ is not available to the JVM.

we can also resolve above exception by adding the font which is missing in our Jasperreports-font.X.X.X.jar Library. So let us have look on this method in detail.

Method 2 : by adding missing font property.
To add missing fonts into the library we can create our own custom library for Jasperreports-font.X.X.X.jar. So follow below given steps to create your custom font library for Jasper Report Font with the help of iReport.

Step 1:
To install missing fonts in iReport go to ” Tools >> Options >> Fonts >> Install Font ” as shown in following screenshot.

Blog2_2

Step 2:
Add your fonts ttf file from browse button and click on Next button as shown in following screenshot.

Blog2_3

Step 3:
After adding fonts ttf file, you need to add family details by adding Bold, Italic and Bold-Italic version of font. If you have not added these version of fonts then it will not change the font style even if we add in our report design. Click on next button after adding the font family version ttf files as shown in following screenshot.

Blog2_4

Step 4:
In this step select the locale for your region, In this example I have added English(India) as shown in following screenshot.

Blog2_5

Step 5:
After that you can also manage the font mapping for avoiding the missing font property in OS.
as it is not mandatory you can skip this and click on finish button as shown in following screenshot.

Blog2_6

Step 6:
You can add multiple fonts by repeating step 2 to 5. After adding all required fonts click on Export as Extension button and save the the library with .jar Extension. as shown in following screenshot.

Blog2_7

Step 7:
After following all above steps you will get the your custom library with all your fonts.

Blog2_8

Now you can use this jar for Jasperreports-font.X.X.X.jar which will be present in your project library or classpath. After replacing this library you will get the your desire output with proper fonts.

Hope this blog will help you to add new font in Jasper Font Library to remove font dependency.

Please don’t forget to comment your feedback for this post 🙂

Remove font dependency in Jasper Report.

In this blog we are going to learn cool stuff which will help us to Remove font dependency in Jasper Report Font Library. So let us see how we can remove the font dependency from Jasper Report Java Application. First of all let us see why we are going to remove the font dependency from Jasper.
So Answer is here,

Jasper Report requires 2 libraries for generating any report,
1. Jasperreport.X.X.X.jar
2. Jasperreports-font.X.X.X.jar

when we are create any Jasper Report application then it requires some fonts for writing data in export phase, so it will take the font from Jasperreports-font.X.X.X.jar library. Generally Jasperreports-font.X.X.X.jar library has some default fonts shown in below screenshot.

Blog2_1

There are following default fonts in Jasper Report library

  • DejaVu Sans
  • DejaVe Sans Mono
  • DejaVu Serif
  • Monospaced
  • SansSerif
  • Serif

For each above font there are 4 different font’s .ttf files are present for font faces which are used for Normal, Bold, Italic and Bold-Italic style. If we have used any font which is not present in our Jasperreports-font.X.X.X.jar library then it will throw an exception something like

net.sf.jasperreports.engine.util.JRFontNotFoundException:
Font ‘Font_Name’ is not available to the JVM.

This exception occurs due to unavailability of font in Jasper report font library. We can not move further until and unless resolve this exception, So now we will learn how to avoid such types of exception while playing with Jasper Report and different types of Fonts.

There are two method to avoid such a problem.
Method 1 : by setting ignore missing font property and default font property.
Method 2 : by adding missing font property.
We will see Method 2 into next blog. For Now Let us focus on Method 1 in detail.

In this method we can avoid above exception by ignoring the missing font property and using default font instead of missing font from our Jasperreports-font.X.X.X.jar library. In Jasper Report library all properties are already defined in default.jasperreports.properties file. There is one property present “net.sf.jasperreports.awt.ignore.missing.font” which help us to remove font dependency from Jasper Report design but it is by default set to “false”. If we try to export with this setting and at the time of filling data in report, Jasper Report fill manager fails to find the mentioned font in Jasper Report design then it will throws an exception which is mentioned earlier in this blog.
So we can avoid missing font exception by setting following property in Java Code.

JRProperties.setProperty("net.sf.jasperreports.awt.ignore.missing.font", "true");

or we can set this property by entering following line into .jrxml file.

<property name="net.sf.jasperreports.awt.ignore.missing.font" value="true"/>

By using above code we can remove font dependency but for exporting report Jasper Needs default font which will use instead of missing fonts. Default Font property is also predefined into default.jasperreports.properties file with the property “net.sf.jasperreports.default.font.name”. We can use the default font in place of our missing font which is mentioned in Jasper Report library. The value of default font is set to “SansSerif”, If we want any other font for it then we can change it manually.

For setting any default font name, we can set following property in Java Code.

JRProperties.setProperty("net.sf.jasperreports.default.font.name", "Default_Font_Name");

or we can set this property by entering following line into .jrxml file.

<property name="net.sf.jasperreports.default.font.name" value="Default_Font_Name"/>

In this way we can add above properties into our application which help us to remove the font dependency from Jasper Report. In next blog we will see the how to add our fonts in Jasper Report Font Library.

Hope this blog will help you to remove font dependency in Jasper Report Font Library.

Please don’t forget to comment your feedback for this post 🙂

How to add alphabetical sequence in Jasper Report.

In this blog we are going to learn one interesting topic of Jasper Report technology. We are going to generate and add alphabetical sequence in Jasper Report. So first of all, let us create simple report which includes the numeric sequence for records. Create a simple PDF report with the help of following steps in Java and Jasper.

We are going to create a report which will print the following information of Employees in our PDF.

Serial NumberEmployee NumberEmployee NameEmployee AddressEmployee Salary
11001AjitLatur40,000
21002AmitAurangabad50,000
31003AniketNashik50,000
41004AnupPune60,000
51005HiteshAkurdi40,000
61006KuldeepHyderabad60,000
71007MayurVishrantwadi50,000
81008OmkarRajgurunagar30,000
91009TusharKopargaon60,000
101010VijayShirdo50,000

So, we will start with the Design part first,

Step 1:
Create a new report in Jasper with blank A4 template. If you are new in Jasper Report then you can refer our tutorial of Jasper from here. Jasper Tutorial includes the information of all the necessary environment setup and provide the guidance for creating a simple report in Jasper and Java.

So now we directly jump to design phase in iReport. Here we are going to design report in Java language hence change the language of report to Java. To change the language click on report in Report Inspector Window and find the language property in Properties window of iReport, by default it is set to Groovy language, click on combo box and change it to Java, as show in following screenshot.

chapter5_0

Step 2:

We are going to display the information of Employees which is filled in above table, we are going to use Field component of Jasper which are the placeholder and it will stored the values which we want to display in our report. These value will be set with the help of Java POJO classes which we will see in the later part in this blog.
For adding the field go into the Report Inspector Window of iReport and click Right Button of mouse on Field and select the “Add Field” option to add the field in report as shown following screenshot.

chapter5_1

Step 3:

After that select added field and rename it by selecting rename option. Jasper provide multiple datatypes for field, parameters and variables. You can change the datatype of Field from property window of iReport. In this chapter we are going to use string datatype to generate the report and String is Default datatype for any field, variable or parameter, hence I am not going to change the datatype. If you want different datatype then you can select the field and change the datatype which you want in your report as shown in following screenshot.

chapter5_2

Step 4:

In this chapter we are just putting the values which is set from Java side so we will remove the other band except Detail and Column Header Band. So drag and drop the required fields in Detail Band. When you add the fields in the Detail Band, we get an option to which value should be display in the field section, mean value which is stored by field or you can show count of the selected field as shown in following screenshot.

chapter5_3

Step 5:

When you used drag and drop method for adding the field in Detail Band of report then Static Text is automatically gets added in the Column Header of report with the label name as Default text in it.

chapter5_4

Step 6:

We can change it by double click in the static text. so we will change the Header labels to standardise our report with proper Header names, After changing the the labels our report design will looks as shown in following screenshot.

chapter5_5

Step 7:

Now lets move to the actual part on our blog. We have to add Sequence Number in our Report. We can also manage the sequence by adding one extra field for sequence number and set value of it from Java. But in case of grouping it will not works properly. Because when we use the grouping concept then Jasper have ability to group the records on the basis of field which is used for grouping and these grouping can be break our sequence if we not handled it from Java. So we will handle these sequence in Jasper instead of Java by using some build in Variable provided by Jasper.

Hence as shown in below screenshot, we are going to use the build in variable REPORT_COUNT to generate the sequence number for each record of our report.

Blog1_1

Now, we can see the generated sample XML code (.jrxml) in XML view of iReport. Our jrxml file is

<?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="report2" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<field name="employeeNumber" class="java.lang.String"/>
<field name="employeeName" class="java.lang.String"/>
<field name="employeeAddress" class="java.lang.String"/>
<field name="employeeSalary" class="java.lang.String"/>
<columnHeader>
<band height="30">
    <staticText>
            <reportElement x="106" y="5" width="100" height="20"/>
            <textElement>
                    <font size="8" isBold="true"/>
            </textElement>
            <text><![CDATA[Employee Number]]></text>
    </staticText>
    <staticText>
            <reportElement x="218" y="5" width="100" height="20"/>
            <textElement>
                    <font size="8" isBold="true"/>
            </textElement>
            <text><![CDATA[Employee Name]]></text>
    </staticText>
    <staticText>
            <reportElement x="328" y="5" width="100" height="20"/>
            <textElement>
                    <font size="8" isBold="true"/>
            </textElement>
            <text><![CDATA[Employee Address]]></text>
    </staticText>
    <staticText>
            <reportElement x="439" y="5" width="100" height="20"/>
            <textElement>
                    <font size="8" isBold="true"/>
            </textElement>
            <text><![CDATA[Employee Salary]]></text>
    </staticText>
    <staticText>
            <reportElement x="6" y="5" width="89" height="20"/>
            <textElement>
                    <font size="8" isBold="true"/>
            </textElement>
            <text><![CDATA[Sr. Number]]></text>
    </staticText>
</band>
</columnHeader>
<detail>
<band height="26">
    <textField>
            <reportElement x="106" y="6" width="100" height="20"/>
            <textElement>
                    <font size="8"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{employeeNumber}]]></textFieldExpression>
    </textField>
    <textField>
            <reportElement x="218" y="6" width="100" height="20"/>
            <textElement>
                    <font size="8"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{employeeName}]]></textFieldExpression>
    </textField>
    <textField>
            <reportElement x="328" y="6" width="100" height="20"/>
            <textElement>
                    <font size="8"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{employeeAddress}]]></textFieldExpression>
    </textField>
    <textField>
            <reportElement x="439" y="6" width="100" height="20"/>
            <textElement>
                    <font size="8"/>
            </textElement>
            <textFieldExpression><![CDATA[$F{employeeSalary}]]></textFieldExpression>
    </textField>
    <textField>
            <reportElement x="6" y="6" width="89" height="20"/>
            <textElement>
                    <font size="8"/>
            </textElement>
            <textFieldExpression><![CDATA[$V{REPORT_COUNT}]]></textFieldExpression>
    </textField>
</band>
</detail>
</jasperReport>

We have finished the design phase of report, now let us move on to the Java side.
Step 1:
Create new project by selecting the simple Java Application Setting and add all the necessary libraries which is described in our Jasper Tutorial.

Step 2:
We have to display the multiple records by using Java POJO classes, so create a new class with name Employee and create the variables with the same name and datatype which was we used in .jrxml file. Create getter and setter method for each variable.

package com.refermycode.mypackage;
/*
* @author Mayur
*/

public class Employee {
String employeeNumber = "";
String employeeName = "";
String employeeAddress = "";
String employeeSalary = "";
public String getEmployeeAddress() {
return employeeAddress;
}
public void setEmployeeAddress(String employeeAddress) {
this.employeeAddress = employeeAddress;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(String employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getEmployeeSalary() {
return employeeSalary;
}
public void setEmployeeSalary(String employeeSalary) {
this.employeeSalary = employeeSalary;
}
}

Step 3:
In main class add the following code to generate the PFD.

package com.refermycode.mypackage;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

/*
* @author Mayur
*/

public class JasperTutorial2 {

public static List addEmployeeInfo() {
List employeeList = new ArrayList();

Employee employee = new Employee();
employee.setEmployeeNumber("1001");
employee.setEmployeeName("Ajit");
employee.setEmployeeAddress("Latur");
employee.setEmployeeSalary("40,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1002");
employee.setEmployeeName("Amit");
employee.setEmployeeAddress("Aurangabad");
employee.setEmployeeSalary("50,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1004");
employee.setEmployeeName("Aniket");
employee.setEmployeeAddress("Nashik");
employee.setEmployeeSalary("50,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1004");
employee.setEmployeeName("Anup");
employee.setEmployeeAddress("Pune");
employee.setEmployeeSalary("60,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1005");
employee.setEmployeeName("Hitesh");
employee.setEmployeeAddress("Akurdi");
employee.setEmployeeSalary("50,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1006");
employee.setEmployeeName("Kuldeep");
employee.setEmployeeAddress("Hyderabad");
employee.setEmployeeSalary("60,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1007");
employee.setEmployeeName("Mayur");
employee.setEmployeeAddress("Vishrantwadi");
employee.setEmployeeSalary("50,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1008");
employee.setEmployeeName("Omkar");
employee.setEmployeeAddress("Rajgurunagar");
employee.setEmployeeSalary("30,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1009");
employee.setEmployeeName("Tushar");
employee.setEmployeeAddress("Kopargaon");
employee.setEmployeeSalary("60,000");
employeeList.add(employee);

employee = new Employee();
employee.setEmployeeNumber("1010");
employee.setEmployeeName("Vijay");
employee.setEmployeeAddress("Shirdi");
employee.setEmployeeSalary("60,000");
employeeList.add(employee);

return employeeList;
}

public static void main(String[] args) throws FileNotFoundException {
try {
InputStream inputStream = new FileInputStream("C:/JasperTutorial2/src/com/refermycode/mypackage/Report2.jrxml");
JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);

HashMap parameters = new HashMap();
List employeeList = addEmployeeInfo();
JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(employeeList);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, beanColDataSource);
JasperExportManager.exportReportToPdfFile(jasperPrint, "C:/test_jasper.pdf");
} catch (JRException ex) {
Logger.getLogger(JasperTutorial2.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

If you want to know how above code is work then refer the page of our Tutorials from Here.

When we execute above code then Jasper will generate the desire output with help of Java POJO classes and collection framework.

Following is the generated sample pdf of our above code.

Blog1_2

This is the way to generate Numerical Sequence for records in Jasper Report.

Now the actual implementation of this blog is started from here.

To generate alphabetical sequence for records,We need to made some changes in Jasper as well as Java. So let us make changes in Java code first.

Create one ArrayList which include the Alphabets which we need to print instead of Number and put it into the map of parameters with the name “characterList”.

List characters = new ArrayList(26);
for (char c = ‘A’; c &lt;= ‘Z’ ; c++) {
characters.add(String.valueOf(c));
}
parametersMap.put("charactersList", characters);

That is sufficient from Java code. Now we also need to made some changes in design. So add the parameter in the design as shown in following screenshot and give name same as given in Java code, i.e. “characterList”.

Blog1_3

Replace the expression of text field which print the sequence number by following code as shown in following screenshot.

$P{charactersList}.get(($V{REPORT_COUNT}1)%26)

This code will replace the numeric values by alphabets and after 26 character it will start sequence from first alphabet again.

Blog1_4

After this run the program and find the generated PDF which includes the alphabetical sequence which is set in ArrayList ‘charactersList’ as shown in following screenshot.

Blog1_5

Hope this blog is help you to generate custom sequence in your Jasper Report.

Please don’t forget to comment your feedback for this post 🙂