How Easily Generate PDF reports from HTML using Java, Spring Boot
Core Idea: This article demonstrates how to create PDF reports from HTML content within a Java Spring Boot application.
Problem: Many applications need to generate reports, and PDFs are a common format. HTML provides a flexible way to design these reports.
Solution: Using Java Spring Boot, FreeMarker templating, and Flying Saucer (xhtmlrenderer) libraries, you can convert HTML to PDF easily.
Steps:
Assuming you have a basic Spring Boot project set up, proceed with the following steps.
Add the following dependency to your Maven project.
<!-- For templating HTML with dynamic data. -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>3.4.3</version>
</dependency>
<!-- To convert HTML to PDF. -->
<dependency>
<groupId>org.xhtmlrenderer</groupId>
<artifactId>flying-saucer-pdf</artifactId>
<version>9.11.4</version>
</dependency>
Create your HTML content file in the resources/templates directory with an .ftl extension. Use FreeMarker's ${} notation to insert dynamic data into the HTML.
<!DOCTYPE html>
<html lang="en">
/* HTML content */
</html>
Enable FreeMarker and set the template location in your application properties file:
spring.application.name=demo
server.servlet.context-path=/demo
spring.freemarker.enabled=true
spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.charset=UTF-8
Defines the contract for report generation.
public interface ReportService {
// Methods for report generation
}
Provide common functionality for report generation.
public abstract class AbstractBaseReportService implements ReportService {
// Common report generation logic
}
Extends `AbstractBaseReportService` and provides specific data and the HTML template for the report.
@Service
public final class StatementReport extends AbstractBaseReportService {
// Implementation details
}
Likewise, the above code design, you can generate a PDF for multiple purposes by providing a concrete implementation as per your need.
Expose an endpoint (/report) to trigger PDF generation.
The controller will utilize the StatementReport service to generate the PDF and then return the PDF as a response.
@RestController
public class ReportController {
// Endpoint to generate and return the PDF
}
Here is a GitHub Gist of complete code. Include these files in your project and generate a PDF of a sample customer.
Feel free to write your comments and suggestions in the comments box.
Cool