Creating a Jasper Report with Spring Boot
This tutorial will guide you through the process of creating a Jasper Report using Spring Boot.
1. Introduction
Jasper Reports is an open-source reporting library that allows developers to generate rich, dynamic, and customizable reports. It provides a powerful set of features for designing and rendering reports in various formats, such as PDF, HTML, Excel, etc. On the other hand, Spring Boot is a popular Java framework for building standalone, production-grade applications with ease.
Our goal is to create a web application that generates a report using Jasper Reports. The application will utilize the Spring Boot framework to handle the backend operations and integrate Jasper Reports for report generation.
We will start by setting up a new Spring Boot project and configuring the necessary dependencies. Then, we will design a report template using the JasperSoft Studio, a powerful visual report designer for Jasper Reports. Next, we will fetch data from a data source (e.g., a database) to populate the report. Once the data is retrieved, we will generate the report using the Jasper Reports API. Finally, we will display the generated report in a web application and explore options to export the report to different formats.
Throughout the tutorial, we will provide code examples and explanations to help you understand each step clearly. By the end, you will have a working Spring Boot application that is creating and displaying Jasper Report.
2. Setting up a Spring Boot Project
To begin, we need to set up a new Spring Boot project. You can use your preferred IDE or create the project from scratch using Maven or Gradle.
Here’s an example of a basic pom.xml
file for a Maven-based Spring Boot project:
<!-- Add the parent Spring Boot starter --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.2</version> </parent> <!-- Add the necessary dependencies --> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Add other dependencies if needed --> </dependencies>
Make sure to adjust the Spring Boot version according to your preference or project requirements.
3. Adding Jasper Reports Dependencies
In this section, we will add the necessary dependencies to integrate Jasper Reports into our Spring Boot project.
Jasper Reports provides a set of libraries and tools for report generation. To include these dependencies in our project, we need to update the pom.xml
file with the following Maven dependencies:
<dependencies> <!-- Spring Boot Web Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Jasper Reports --> <dependency> <groupId>net.sf.jasperreports</groupId> <artifactId>jasperreports</artifactId> <version>6.17.0</version> </dependency> <dependency> <groupId>net.sf.jasperreports</groupId> <artifactId>jasperreports-fonts</artifactId> <version>6.17.0</version> </dependency> </dependencies>
In the above example, we have added the Spring Boot Web Starter dependency as well as the Jasper Reports dependencies. The jasperreports
artifact provides the core libraries for working with Jasper Reports, and the jasperreports-fonts
artifact includes additional fonts that might be needed for rendering reports.
Once you have added the dependencies, save the pom.xml
file and let Maven download the necessary JAR files.
Now that we have the dependencies set up, let’s move on to designing the report template using JasperSoft Studio in the next section.
4. Designing the Report Template
In this section, we will design the report template using JasperSoft Studio. JasperSoft Studio is a visual report designer that allows us to create and customize the layout of our reports.
To get started, you can download and install JasperSoft Studio from the official website. Once installed, follow these steps:
- Open JasperSoft Studio and create a new project.
- Right-click on the project and select “New Jasper Report.”
- Provide a name for the report and choose the desired template (e.g., Blank A4).
- In the report editor, you can add elements such as text fields, images, tables, and charts to design the report layout.
- Customize the appearance of the elements by adjusting properties like font, color, size, etc.
- Bind the report elements to data fields by dragging and dropping them from the “Palette” onto the report.
- Save the report template.
Once you have designed the report template, we need to import it into our Spring Boot project. Create a new directory src/main/resources/reports
and place the report template file (with the .jrxml
extension) inside it.
5. Fetching Data for the Report
In this section, we will fetch data from a data source to populate the report. For simplicity, let’s assume we have a list of employees and we want to display their details in the report.
First, create an Employee
class representing the employee entity:
public class Employee { private String firstName; private String lastName; private String designation; // Getters and setters }
Next, create a service or repository class to fetch the employee data. For demonstration purposes, we will create a simple service class:
@Service public class EmployeeService { public List<Employee> getAllEmployees() { // Fetch employee data from a data source (e.g., database) // Return the list of employees } }
Make sure to inject the EmployeeService
wherever you need to retrieve the employee data.
6. Generating the Jasper Report
In this section, we will generate the Jasper Report using the report template and the fetched employee data.
First, let’s create a service class responsible for generating the report:
@Service public class ReportService { private final EmployeeService employeeService; public ReportService(EmployeeService employeeService) { this.employeeService = employeeService; } public byte[] generateReport() throws Exception { List<Employee> employees = employeeService.getAllEmployees(); // Load the report template InputStream reportTemplate = getClass().getResourceAsStream("/reports/employeeReport.jrxml"); // Compile the report template JasperReport jasperReport = JasperCompileManager.compileReport(reportTemplate); // Convert the list of employees to a JRBeanCollectionDataSource JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(employees); // Generate the report using the compiled template and data source JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, dataSource); // Export the report to a byte array (PDF format) byte[] reportBytes = JasperExportManager.exportReportToPdf(jasperPrint); return reportBytes; } }
In the above example, we inject the EmployeeService
to fetch the employee data. We load the report template, compile it using JasperCompileManager
, and convert the list of employees to a JRBeanCollectionDataSource
. Finally, we generate the report using JasperFillManager
and export it to a byte array (PDF format) using JasperExportManager
.
Note: In a real-world scenario, you may need to pass additional parameters to the report or apply more complex logic. The above code provides a basic example to get you started.
7. Displaying the Report in a Web Application
In this section, we will create a Spring MVC controller to handle the report generation and display it in a web application.
First, let’s create the controller class:
@Controller public class ReportController { private final ReportService reportService; public ReportController(ReportService reportService) { this.reportService = reportService; } @GetMapping("/report") public void generateReport(HttpServletResponse response) throws Exception { byte[] reportBytes = reportService.generateReport(); // Set the response headers response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "inline; filename=employeeReport.pdf"); // Write the report bytes to the response output stream OutputStream outputStream = response.getOutputStream(); outputStream.write(reportBytes); outputStream.flush(); } }
In the above example, we create a generateReport
method mapped to the /report
URL using the @GetMapping
annotation. Inside the method, we obtain the generated report bytes from the ReportService
and set the necessary response headers. Finally, we write the report bytes to the response output stream.
Now, when you access the /report
URL in your web application, it will generate and display the Jasper Report.
In the next section, we will explore options to export the report to different formats.
8. Exporting the Report to Different Formats
In this section, we will enhance our application to export the report to different formats, such as Excel and HTML.
First, let’s modify the ReportService
to include methods for generating reports in different formats:
@Service public class ReportService { // Existing code public byte[] generateReportAsExcel() throws Exception { List<Employee> employees = employeeService.getAllEmployees(); InputStream reportTemplate = getClass().getResourceAsStream("/reports/employeeReport.jrxml"); JasperReport jasperReport = JasperCompileManager.compileReport(reportTemplate); JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(employees); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, dataSource); byte[] reportBytes = JasperExportManager.exportReportToPdf(jasperPrint); return reportBytes; } public byte[] generateReportAsHtml() throws Exception { List<Employee> employees = employeeService.getAllEmployees(); InputStream reportTemplate = getClass().getResourceAsStream("/reports/employeeReport.jrxml"); JasperReport jasperReport = JasperCompileManager.compileReport(reportTemplate); JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(employees); JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, null, dataSource); byte[] reportBytes = JasperExportManager.exportReportToPdf(jasperPrint); return reportBytes; } }
In the above example, we added two new methods: generateReportAsExcel
and generateReportAsHtml
. These methods follow a similar pattern to the existing generateReport
method, but export the report to Excel and HTML formats, respectively, using the JasperExportManager.exportReportToXlsx
and JasperExportManager.exportReportToHtml
methods.
Next, modify the ReportController
to handle the export functionality:
@Controller public class ReportController { // Existing code @GetMapping("/report/excel") public void generateReportAsExcel(HttpServletResponse response) throws Exception { byte[] reportBytes = reportService.generateReportAsExcel(); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-Disposition", "attachment; filename=employeeReport.xlsx"); OutputStream outputStream = response.getOutputStream(); outputStream.write(reportBytes); outputStream.flush(); } @GetMapping("/report/html") public void generateReportAsHtml(HttpServletResponse response) throws Exception { byte[] reportBytes = reportService.generateReportAsHtml(); response.setContentType("text/html"); response.setHeader("Content-Disposition", "attachment; filename=employeeReport.html"); OutputStream outputStream = response.getOutputStream(); outputStream.write(reportBytes); outputStream.flush(); } }
In the above example, we added two new methods in the ReportController
: generateReportAsExcel
and generateReportAsHtml
. These methods handle the export of the report to Excel and HTML formats, respectively. We set the appropriate response headers based on the desired format and write the report bytes to the response output stream.
Now, you can access the /report/excel
and /report/html
URLs in your web application to download the report in Excel and HTML formats, respectively.
9. Conclusion
In this tutorial, we have learned about creating a Jasper Report with Spring Boot. We started by setting up a Spring Boot project and adding the necessary dependencies for Jasper Reports. Then, we designed a report template using JasperSoft Studio and fetched data from a data source to populate the report.
By following the steps outlined in this tutorial, you should now have a good understanding of how to create Jasper Reports with Spring Boot and leverage its powerful reporting capabilities in your applications. Feel free to experiment and enhance the application further based on your specific requirements.