{{announcement.body}}
{{announcement.title}}

Spring Boot — Jasper Integration

DZone 's Guide to

Spring Boot — Jasper Integration

In this article, learn how to integrate Spring Boot with Jasper.

· Integration Zone ·
Free Resource

Learn how to integrate Spring Boot with Jasper. JasperReports is an open source reporting engine. It provides the ability to deliver rich content to the printer, the screen, or to 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.

You may also like:  Java Reporting With Jasper Reports - Part 2

Model — Class holds Employee. Maven Dependency:

XML
xxxxxxxxxx
1
29
 
1
<dependencies>
2
    <dependency>
3
        <groupId>org.springframework.boot</groupId>
4
        <artifactId>spring-boot-starter-web</artifactId>
5
    </dependency>
6
    <dependency>
7
        <groupId>net.sf.jasperreports</groupId>
8
        <artifactId>jasperreports</artifactId>
9
        <version>6.4.0</version>
10
    </dependency>
11
    <dependency>
12
        <groupId>org.projectlombok</groupId>
13
        <artifactId>lombok</artifactId>
14
    </dependency>
15
    <dependency>
16
        <groupId>org.springframework.boot</groupId>
17
        <artifactId>spring-boot-starter-data-jpa</artifactId>
18
    </dependency>
19
    <dependency>
20
        <groupId>com.h2database</groupId>
21
        <artifactId>h2</artifactId>
22
        <scope>runtime</scope>
23
    </dependency>
24
    <dependency>
25
        <groupId>org.apache.poi</groupId>
26
        <artifactId>poi</artifactId>
27
        <version>4.1.1</version>
28
    </dependency>
29
</dependencies>


Model — Class holds Employee.

Java
xxxxxxxxxx
1
15
 
1
@Builder
2
@Data
3
@AllArgsConstructor
4
@NoArgsConstructor
5
@Entity
6
@Table(name="EMPLOYEE")
7
public class Employee {
8
    @Id
9
    @GeneratedValue(strategy = GenerationType.IDENTITY)
10
    private int id;
11
    private String name;
12
    private String oraganization;
13
    private String designation;
14
    private int salary;
15
}


EmployeeController — Which has information about the Employee Report endpoint.

Java
xxxxxxxxxx
1
24
 
1
package org.websparrow.report.controller;
2
 
          
3
 
          
4
import org.springframework.beans.factory.annotation.Autowired;
5
import org.springframework.web.bind.annotation.GetMapping;
6
import org.springframework.web.bind.annotation.RequestMapping;
7
import org.springframework.web.bind.annotation.RestController;
8
import org.websparrow.report.service.EmployeeReportService;
9
 
          
10
 
          
11
@RestController
12
@RequestMapping("/employee")
13
public class EmpReportController {
14
 
          
15
 
          
16
    @Autowired
17
    private EmployeeReportService employeeReportService;
18
 
          
19
 
          
20
    @GetMapping("/report")
21
    public String empReport() {
22
        return employeeReportService.generateReport();
23
    }
24
}


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

Java
xxxxxxxxxx
1
11
 
1
package org.websparrow.report.repository;
2
 
          
3
 
          
4
import org.springframework.data.jpa.repository.JpaRepository;
5
import org.websparrow.report.dto.Employee;
6
 
          
7
 
          
8
public interface EmployeeRepository extends JpaRepository<Employee, Long>{
9
 
          
10
 
          
11
}


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

Java
xxxxxxxxxx
1
128
 
1
package org.websparrow.report.service;
2
 
          
3
 
          
4
import java.io.File;
5
import java.io.FileInputStream;
6
import java.io.InputStream;
7
import java.util.ArrayList;
8
import java.util.HashMap;
9
import java.util.List;
10
import java.util.Map;
11
 
          
12
 
          
13
import org.springframework.beans.factory.annotation.Autowired;
14
import org.springframework.beans.factory.annotation.Value;
15
import org.springframework.stereotype.Service;
16
import org.springframework.util.ResourceUtils;
17
import org.websparrow.report.dto.Employee;
18
import org.websparrow.report.repository.EmployeeRepository;
19
 
          
20
 
          
21
import net.sf.jasperreports.engine.JRException;
22
import net.sf.jasperreports.engine.JasperCompileManager;
23
import net.sf.jasperreports.engine.JasperExportManager;
24
import net.sf.jasperreports.engine.JasperFillManager;
25
import net.sf.jasperreports.engine.JasperPrint;
26
import net.sf.jasperreports.engine.JasperReport;
27
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
28
import net.sf.jasperreports.engine.export.JRCsvExporter;
29
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
30
import net.sf.jasperreports.export.SimpleCsvExporterConfiguration;
31
import net.sf.jasperreports.export.SimpleExporterInput;
32
import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
33
import net.sf.jasperreports.export.SimpleWriterExporterOutput;
34
import net.sf.jasperreports.export.SimpleXlsxReportConfiguration;
35
 
          
36
 
          
37
@Service
38
public class EmployeeReportService {
39
 
          
40
 
          
41
    @Value("${report.path}")
42
    private String reportPath;
43
 
          
44
 
          
45
    @Autowired
46
    private EmployeeRepository employeeRepository;
47
 
          
48
 
          
49
    public String generateReport() {
50
        List<Employee> employees = new ArrayList<>();
51
        employeeRepository.findAll().stream().forEach(e -> employees.add(e));
52
 
          
53
 
          
54
        try {
55
            File file = ResourceUtils.getFile("classpath:employee-rpt.jrxml");
56
            InputStream input = new FileInputStream(file);
57
 
          
58
 
          
59
            // Compile the Jasper report from .jrxml to .japser
60
            JasperReport jasperReport = JasperCompileManager.compileReport(input);
61
 
          
62
 
          
63
            // Get your data source
64
            JRBeanCollectionDataSource source = new JRBeanCollectionDataSource(employees);
65
 
          
66
 
          
67
            // Add parameters
68
            Map<String, Object> parameters = new HashMap<>();
69
            parameters.put("createdBy", "JavaHelper.org");
70
 
          
71
 
          
72
            // Fill the report
73
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, source);
74
 
          
75
 
          
76
            // Export the report to a PDF file
77
            JasperExportManager.exportReportToPdfFile(jasperPrint, reportPath + "\\Empployee.pdf");
78
            System.out.println("PDF File Generated !!");
79
 
          
80
 
          
81
            JasperExportManager.exportReportToXmlFile(jasperPrint, reportPath + "\\Employee.xml", true);
82
            System.out.println("XML File Generated !!");
83
 
          
84
 
          
85
            JasperExportManager.exportReportToHtmlFile(jasperPrint, reportPath + "\\Employee.html");
86
            System.out.println("HTML Generated");
87
 
          
88
            xlsx(jasperPrint);
89
            csv(jasperPrint);
90
 
          
91
            return "Report successfully generated @path= " + reportPath;
92
 
          
93
        } catch (Exception e) {
94
            return e.getMessage();
95
        }
96
    }
97
 
          
98
    private void csv(JasperPrint jasperPrint) throws JRException {
99
        JRCsvExporter exporter = new JRCsvExporter();
100
        exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
101
        exporter.setExporterOutput(new SimpleWriterExporterOutput(reportPath + "\\Employee.csv"));
102
 
          
103
 
          
104
        SimpleCsvExporterConfiguration configuration = new SimpleCsvExporterConfiguration();
105
        configuration.setFieldDelimiter(",");
106
        exporter.setConfiguration(configuration);
107
        exporter.exportReport();
108
    }
109
 
          
110
 
          
111
    // Ref: https://www.programcreek.com/java-api-examples/?class=net.sf.jasperreports.export.SimpleXlsxReportConfiguration&method=setOnePagePerSheet
112
    private void xlsx(JasperPrint jasperPrint) throws JRException {
113
        // Exports a JasperReports document to XLSX format. It has character output type and exports the document to a grid-based layout.
114
        JRXlsxExporter exporter = new JRXlsxExporter();
115
        exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
116
        exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(reportPath + "\\Employee.xlsx"));
117
 
          
118
 
          
119
        SimpleXlsxReportConfiguration configuration = new SimpleXlsxReportConfiguration();
120
        configuration.setOnePagePerSheet(true);
121
        configuration.setRemoveEmptySpaceBetweenColumns(true);
122
        configuration.setDetectCellType(true);
123
        exporter.setConfiguration(configuration);
124
 
          
125
 
          
126
        exporter.exportReport();
127
    }
128
}


EmployeeReport — jrxml

XML
xxxxxxxxxx
1
174
1
<?xml version="1.0" encoding="UTF-8"?>
2
<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">
3
    <property name="ireport.zoom" value="1.0"></property>
4
    <property name="ireport.x" value="0"></property>
5
    <property name="ireport.y" value="0"></property>
6
    <parameter name="createdBy" class="java.lang.String"/>
7
    <field name="id" class="java.lang.Integer"></field>
8
    <field name="name" class="java.lang.String"></field>
9
    <field name="oraganization" class="java.lang.String"></field>
10
    <field name="designation" class="java.lang.String"></field>
11
    <field name="salary" class="java.lang.Integer"></field>
12
    <background>
13
        <band splitType="Stretch"></band>
14
    </background>
15
    <title>
16
        <band height="42" splitType="Stretch">
17
            <staticText>
18
                <reportElement x="64" y="0" width="481" height="42"></reportElement>
19
                <textElement textAlignment="Center">
20
                    <font size="20" isBold="true"></font>
21
                </textElement>
22
                <text><![CDATA[Employee Details]]></text>
23
            </staticText>
24
        </band>
25
    </title>
26
    <columnHeader>
27
        <band height="61" splitType="Stretch">
28
            <staticText>
29
                <reportElement x="0" y="41" width="111" height="20"></reportElement>
30
                <box>
31
                    <pen lineWidth="0.25"></pen>
32
                    <topPen lineWidth="0.25"></topPen>
33
                    <leftPen lineWidth="0.25"></leftPen>
34
                    <bottomPen lineWidth="0.25"></bottomPen>
35
                    <rightPen lineWidth="0.25"></rightPen>
36
                </box>
37
                <textElement textAlignment="Center">
38
                    <font size="12" isBold="true" isItalic="false"></font>
39
                </textElement>
40
                <text><![CDATA[ID]]></text>
41
            </staticText>
42
            <staticText>
43
                <reportElement x="111" y="41" width="111" height="20"></reportElement>
44
                <box>
45
                    <pen lineWidth="0.25"></pen>
46
                    <topPen lineWidth="0.25"></topPen>
47
                    <leftPen lineWidth="0.25"></leftPen>
48
                    <bottomPen lineWidth="0.25"></bottomPen>
49
                    <rightPen lineWidth="0.25"></rightPen>
50
                </box>
51
                <textElement textAlignment="Center">
52
                    <font size="12" isBold="true" isItalic="false"></font>
53
                </textElement>
54
                <text><![CDATA[Name]]></text>
55
            </staticText>
56
            <staticText>
57
                <reportElement x="222" y="41" width="111" height="20"></reportElement>
58
                <box>
59
                    <pen lineWidth="0.25"></pen>
60
                    <topPen lineWidth="0.25"></topPen>
61
                    <leftPen lineWidth="0.25"></leftPen>
62
                    <bottomPen lineWidth="0.25"></bottomPen>
63
                    <rightPen lineWidth="0.25"></rightPen>
64
                </box>
65
                <textElement textAlignment="Center">
66
                    <font size="12" isBold="true" isItalic="false"></font>
67
                </textElement>
68
                <text><![CDATA[Oraganization]]></text>
69
            </staticText>
70
            <staticText>
71
                <reportElement x="333" y="41" width="111" height="20"></reportElement>
72
                <box>
73
                    <pen lineWidth="0.25"></pen>
74
                    <topPen lineWidth="0.25"></topPen>
75
                    <leftPen lineWidth="0.25"></leftPen>
76
                    <bottomPen lineWidth="0.25"></bottomPen>
77
                    <rightPen lineWidth="0.25"></rightPen>
78
                </box>
79
                <textElement textAlignment="Center">
80
                    <font size="12" isBold="true" isItalic="false"></font>
81
                </textElement>
82
                <text><![CDATA[Designation]]></text>
83
            </staticText>
84
            <staticText>
85
                <reportElement x="444" y="41" width="111" height="20"></reportElement>
86
                <box>
87
                    <pen lineWidth="0.25"></pen>
88
                    <topPen lineWidth="0.25"></topPen>
89
                    <leftPen lineWidth="0.25"></leftPen>
90
                    <bottomPen lineWidth="0.25"></bottomPen>
91
                    <rightPen lineWidth="0.25"></rightPen>
92
                </box>
93
                <textElement textAlignment="Center">
94
                    <font size="12" isBold="true" isItalic="false"></font>
95
                </textElement>
96
                <text><![CDATA[Salary]]></text>
97
            </staticText>
98
            <textField>
99
                <reportElement x="456" y="21" width="99" height="20"></reportElement>
100
                <textElement></textElement>
101
                <textFieldExpression><![CDATA[$P{createdBy}]]></textFieldExpression>
102
            </textField>
103
            <staticText>
104
                <reportElement x="398" y="21" width="58" height="20"></reportElement>
105
                <textElement></textElement>
106
                <text><![CDATA[Created By:]]></text>
107
            </staticText>
108
        </band>
109
    </columnHeader>
110
    <detail>
111
        <band height="20" splitType="Stretch">
112
            <textField>
113
                <reportElement x="0" y="0" width="111" height="20"></reportElement>
114
                <box>
115
                    <pen lineWidth="0.25"></pen>
116
                    <topPen lineWidth="0.25"></topPen>
117
                    <leftPen lineWidth="0.25"></leftPen>
118
                    <bottomPen lineWidth="0.25"></bottomPen>
119
                    <rightPen lineWidth="0.25"></rightPen>
120
                </box>
121
                <textElement textAlignment="Center"></textElement>
122
                <textFieldExpression><![CDATA[$F{id}]]></textFieldExpression>
123
            </textField>
124
            <textField>
125
                <reportElement x="111" y="0" width="111" height="20"></reportElement>
126
                <box>
127
                    <pen lineWidth="0.25"></pen>
128
                    <topPen lineWidth="0.25"></topPen>
129
                    <leftPen lineWidth="0.25"></leftPen>
130
                    <bottomPen lineWidth="0.25"></bottomPen>
131
                    <rightPen lineWidth="0.25"></rightPen>
132
                </box>
133
                <textElement textAlignment="Center"></textElement>
134
                <textFieldExpression><![CDATA[$F{name}]]></textFieldExpression>
135
            </textField>
136
            <textField>
137
                <reportElement x="222" y="0" width="111" height="20"></reportElement>
138
                <box>
139
                    <pen lineWidth="0.25"></pen>
140
                    <topPen lineWidth="0.25"></topPen>
141
                    <leftPen lineWidth="0.25"></leftPen>
142
                    <bottomPen lineWidth="0.25"></bottomPen>
143
                    <rightPen lineWidth="0.25"></rightPen>
144
                </box>
145
                <textElement textAlignment="Center"></textElement>
146
                <textFieldExpression><![CDATA[$F{oraganization}]]></textFieldExpression>
147
            </textField>
148
            <textField>
149
                <reportElement x="333" y="0" width="111" height="20"></reportElement>
150
                <box>
151
                    <pen lineWidth="0.25"></pen>
152
                    <topPen lineWidth="0.25"></topPen>
153
                    <leftPen lineWidth="0.25"></leftPen>
154
                    <bottomPen lineWidth="0.25"></bottomPen>
155
                    <rightPen lineWidth="0.25"></rightPen>
156
                </box>
157
                <textElement textAlignment="Center"></textElement>
158
                <textFieldExpression><![CDATA[$F{designation}]]></textFieldExpression>
159
            </textField>
160
            <textField>
161
                <reportElement x="444" y="0" width="111" height="20"></reportElement>
162
                <box>
163
                    <pen lineWidth="0.25"></pen>
164
                    <topPen lineWidth="0.25"></topPen>
165
                    <leftPen lineWidth="0.25"></leftPen>
166
                    <bottomPen lineWidth="0.25"></bottomPen>
167
                    <rightPen lineWidth="0.25"></rightPen>
168
                </box>
169
                <textElement textAlignment="Center"></textElement>
170
                <textFieldExpression><![CDATA[$F{salary}]]></textFieldExpression>
171
            </textField>
172
        </band>
173
    </detail>
174
</jasperReport>


MainApp — Run this application as Spring Boot.

Java
xxxxxxxxxx
1
15
 
1
package org.websparrow.report;
2
 
          
3
 
          
4
import org.springframework.boot.SpringApplication;
5
import org.springframework.boot.autoconfigure.SpringBootApplication;
6
 
          
7
 
          
8
@SpringBootApplication
9
public class App  {
10
 
          
11
 
          
12
    public static void main(String[] args) {
13
        SpringApplication.run(App.class, args);
14
    }
15
}


Output:

PDF File


Further Reading

All About Spring Boot [Tutorials and Articles]

JasperReports – Open Source Reporting Tool
Topics:
jasper report ,spring boot 2.2 ,integration ,tutorial ,jasper integration ,spring boot jasper integration

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}