Spring Boot — Jasper Integration

Prateek
5 min readJun 11, 2021

--

Learn how to integrate the Spring Boot with Jasper. 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.

tgitFeatures 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

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>6.4.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.1</version>
</dependency>
</dependencies>

Model — Class holds Employee.

package org.websparrow.report.dto;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="EMPLOYEE")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String oraganization;
private String designation;
private int salary;
}

EmployeeController — Which has information about the Employee Report endpoint.

package org.websparrow.report.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.websparrow.report.service.EmployeeReportService;
@RestController
@RequestMapping("/employee")
public class EmpReportController {
@Autowired
private EmployeeReportService employeeReportService;
@GetMapping("/report")
public String empReport() {
return employeeReportService.generateReport();
}
}

EmployeeRepository — This class talk to database and it implements the JpaRepository

package org.websparrow.report.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.websparrow.report.dto.Employee;
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
}

EmployeeService — Service class which holds the logic of creating reports in XML, HTML, XLSX, CSV etc formats.

package org.websparrow.report.service;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.websparrow.report.dto.Employee;
import org.websparrow.report.repository.EmployeeRepository;
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;
import net.sf.jasperreports.engine.export.JRCsvExporter;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import net.sf.jasperreports.export.SimpleCsvExporterConfiguration;
import net.sf.jasperreports.export.SimpleExporterInput;
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
import net.sf.jasperreports.export.SimpleWriterExporterOutput;
import net.sf.jasperreports.export.SimpleXlsxReportConfiguration;
@Service
public class EmployeeReportService {
@Value("${report.path}")
private String reportPath;
@Autowired
private EmployeeRepository employeeRepository;
public String generateReport() {
List<Employee> employees = new ArrayList<>();
employeeRepository.findAll().stream().forEach(e -> employees.add(e));
try {
File file = ResourceUtils.getFile("classpath:employee-rpt.jrxml");
InputStream input = new FileInputStream(file);
// Compile the Jasper report from .jrxml to .japser
JasperReport jasperReport = JasperCompileManager.compileReport(input);
// Get your data source
JRBeanCollectionDataSource source = new JRBeanCollectionDataSource(employees);
// Add parameters
Map<String, Object> parameters = new HashMap<>();
parameters.put("createdBy", "JavaHelper.org");
// Fill the report
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, source);
// Export the report to a PDF file
JasperExportManager.exportReportToPdfFile(jasperPrint, reportPath + "\\Empployee.pdf");
System.out.println("PDF File Generated !!");
JasperExportManager.exportReportToXmlFile(jasperPrint, reportPath + "\\Employee.xml", true);
System.out.println("XML File Generated !!");
JasperExportManager.exportReportToHtmlFile(jasperPrint, reportPath + "\\Employee.html");
System.out.println("HTML Generated");
xlsx(jasperPrint);
csv(jasperPrint);
return "Report successfully generated @path= " + reportPath; } catch (Exception e) {
return e.getMessage();
}
}
private void csv(JasperPrint jasperPrint) throws JRException {
JRCsvExporter exporter = new JRCsvExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleWriterExporterOutput(reportPath + "\\Employee.csv"));
SimpleCsvExporterConfiguration configuration = new SimpleCsvExporterConfiguration();
configuration.setFieldDelimiter(",");
exporter.setConfiguration(configuration);
exporter.exportReport();
}
// Ref: https://www.programcreek.com/java-api-examples/?class=net.sf.jasperreports.export.SimpleXlsxReportConfiguration&method=setOnePagePerSheet
private void xlsx(JasperPrint jasperPrint) throws JRException {
// Exports a JasperReports document to XLSX format. It has character output type and exports the document to a grid-based layout.
JRXlsxExporter exporter = new JRXlsxExporter();
exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(reportPath + "\\Employee.xlsx"));
SimpleXlsxReportConfiguration configuration = new SimpleXlsxReportConfiguration();
configuration.setOnePagePerSheet(true);
configuration.setRemoveEmptySpaceBetweenColumns(true);
configuration.setDetectCellType(true);
exporter.setConfiguration(configuration);
exporter.exportReport();
}
}

EmployeeReport -jrxml

<?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="employee-rpt" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20">
<property name="ireport.zoom" value="1.0"/>
<property name="ireport.x" value="0"/>
<property name="ireport.y" value="0"/>
<parameter name="createdBy" class="java.lang.String"/>
<field name="id" class="java.lang.Integer"/>
<field name="name" class="java.lang.String"/>
<field name="oraganization" class="java.lang.String"/>
<field name="designation" class="java.lang.String"/>
<field name="salary" class="java.lang.Integer"/>
<background>
<band splitType="Stretch"/>
</background>
<title>
<band height="42" splitType="Stretch">
<staticText>
<reportElement x="64" y="0" width="481" height="42"/>
<textElement textAlignment="Center">
<font size="20" isBold="true"/>
</textElement>
<text><![CDATA[Employee Details]]></text>
</staticText>
</band>
</title>
<columnHeader>
<band height="61" splitType="Stretch">
<staticText>
<reportElement x="0" y="41" width="111" height="20"/>
<box>
<pen lineWidth="0.25"/>
<topPen lineWidth="0.25"/>
<leftPen lineWidth="0.25"/>
<bottomPen lineWidth="0.25"/>
<rightPen lineWidth="0.25"/>
</box>
<textElement textAlignment="Center">
<font size="12" isBold="true" isItalic="false"/>
</textElement>
<text><![CDATA[ID]]></text>
</staticText>
<staticText>
<reportElement x="111" y="41" width="111" height="20"/>
<box>
<pen lineWidth="0.25"/>
<topPen lineWidth="0.25"/>
<leftPen lineWidth="0.25"/>
<bottomPen lineWidth="0.25"/>
<rightPen lineWidth="0.25"/>
</box>
<textElement textAlignment="Center">
<font size="12" isBold="true" isItalic="false"/>
</textElement>
<text><![CDATA[Name]]></text>
</staticText>
<staticText>
<reportElement x="222" y="41" width="111" height="20"/>
<box>
<pen lineWidth="0.25"/>
<topPen lineWidth="0.25"/>
<leftPen lineWidth="0.25"/>
<bottomPen lineWidth="0.25"/>
<rightPen lineWidth="0.25"/>
</box>
<textElement textAlignment="Center">
<font size="12" isBold="true" isItalic="false"/>
</textElement>
<text><![CDATA[Oraganization]]></text>
</staticText>
<staticText>
<reportElement x="333" y="41" width="111" height="20"/>
<box>
<pen lineWidth="0.25"/>
<topPen lineWidth="0.25"/>
<leftPen lineWidth="0.25"/>
<bottomPen lineWidth="0.25"/>
<rightPen lineWidth="0.25"/>
</box>
<textElement textAlignment="Center">
<font size="12" isBold="true" isItalic="false"/>
</textElement>
<text><![CDATA[Designation]]></text>
</staticText>
<staticText>
<reportElement x="444" y="41" width="111" height="20"/>
<box>
<pen lineWidth="0.25"/>
<topPen lineWidth="0.25"/>
<leftPen lineWidth="0.25"/>
<bottomPen lineWidth="0.25"/>
<rightPen lineWidth="0.25"/>
</box>
<textElement textAlignment="Center">
<font size="12" isBold="true" isItalic="false"/>
</textElement>
<text><![CDATA[Salary]]></text>
</staticText>
<textField>
<reportElement x="456" y="21" width="99" height="20"/>
<textElement/>
<textFieldExpression><![CDATA[$P{createdBy}]]></textFieldExpression>
</textField>
<staticText>
<reportElement x="398" y="21" width="58" height="20"/>
<textElement/>
<text><![CDATA[Created By:]]></text>
</staticText>
</band>
</columnHeader>
<detail>
<band height="20" splitType="Stretch">
<textField>
<reportElement x="0" y="0" width="111" height="20"/>
<box>
<pen lineWidth="0.25"/>
<topPen lineWidth="0.25"/>
<leftPen lineWidth="0.25"/>
<bottomPen lineWidth="0.25"/>
<rightPen lineWidth="0.25"/>
</box>
<textElement textAlignment="Center"/>
<textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="111" y="0" width="111" height="20"/>
<box>
<pen lineWidth="0.25"/>
<topPen lineWidth="0.25"/>
<leftPen lineWidth="0.25"/>
<bottomPen lineWidth="0.25"/>
<rightPen lineWidth="0.25"/>
</box>
<textElement textAlignment="Center"/>
<textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="222" y="0" width="111" height="20"/>
<box>
<pen lineWidth="0.25"/>
<topPen lineWidth="0.25"/>
<leftPen lineWidth="0.25"/>
<bottomPen lineWidth="0.25"/>
<rightPen lineWidth="0.25"/>
</box>
<textElement textAlignment="Center"/>
<textFieldExpression><![CDATA[$F{oraganization}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="333" y="0" width="111" height="20"/>
<box>
<pen lineWidth="0.25"/>
<topPen lineWidth="0.25"/>
<leftPen lineWidth="0.25"/>
<bottomPen lineWidth="0.25"/>
<rightPen lineWidth="0.25"/>
</box>
<textElement textAlignment="Center"/>
<textFieldExpression><![CDATA[$F{designation}]]></textFieldExpression>
</textField>
<textField>
<reportElement x="444" y="0" width="111" height="20"/>
<box>
<pen lineWidth="0.25"/>
<topPen lineWidth="0.25"/>
<leftPen lineWidth="0.25"/>
<bottomPen lineWidth="0.25"/>
<rightPen lineWidth="0.25"/>
</box>
<textElement textAlignment="Center"/>
<textFieldExpression><![CDATA[$F{salary}]]></textFieldExpression>
</textField>
</band>
</detail>
</jasperReport>

MainApp — Run this application as spring boot.

package org.websparrow.report;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}

Output — PDF File

CSV

HTML

XLS

--

--

Prateek
Prateek

Written by Prateek

Java Developer and enthusiast

No responses yet