How to generate PDF report from MySQL database in Spring Boot

I am going to show yo how to download PDF file from MySQL database using Spring Boot and iText library in Java programming language. Many applications require dynamic generation of PDF documents for reporting purpose, such as, generating statements for customers, readers buying online specific chapters of a book, etc.

In my another tutorial I had shown how to create or write to a PDF file using Java based iText library. The iText library is freely available and can be used using maven or gradle build tool. We can also generate HTML, RTF, XML documents using iText library apart from PDF documents.

PDF files can be useful for various reasons:

  • layout is uniform across different computer systems
  • tend to have a small file size in comparison to other file formats
  • can be protected by password
  • different levels of access can be set based on requirements
  • works uniformly across different operating systems
  • graphics or images, links, etc. can be easily integrated


Java at least 8, Gradle 6.5.1, Maven 3.6.3, iText, Spring Boot 2.3.3, MySQL 8.0.17

Project Setup

You can create gradle or maven based project in your favorite IDE or tool. According to your gradle or maven based project you can use one of the following build file.

You need to add additional jaxb runtime API if you are using MySQL 8 and Java higher than version 8.


buildscript {
	ext {
		springBootVersion = '2.3.3.RELEASE'
    repositories {
    dependencies {

plugins {
    id 'java-library'
    id 'org.springframework.boot' version "${springBootVersion}"

sourceCompatibility = 12
targetCompatibility = 12

repositories {

dependencies {
	implementation 'mysql:mysql-connector-java:8.0.21'
    //required for JDK 9 or above
    implementation 'javax.xml.bind:jaxb-api:2.4.0-b180830.0359'


<project xmlns=""




		<!--required only if jdk 9 or higher version is used-->

					<source>at least 8</source>
					<target>at least 8</target>

MySQL Data

As I am going to test the application right away once coding part is done, so I have stored some sample data in MySQL table product under database roytuts as shown below.

In MySQL version 8 you do not need to specify the size of the int data type. If you do so then MySQL server will give you warning.

CREATE TABLE `product` (
	`id` int unsigned COLLATE utf8mb4_unicode_ci NOT NULL AUTO_INCREMENT,
	`name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
	`price` double COLLATE utf8mb4_unicode_ci NOT NULL,
	`sale_price` double COLLATE utf8mb4_unicode_ci NOT NULL,
	`sales_count` int unsigned COLLATE utf8mb4_unicode_ci NOT NULL,
	`sale_date` VARCHAR(20) NOT NULL,

insert into product(id,name,price,sale_price,sales_count,sale_date) values(1, 'Desktop','30000','35000','55','02-04-2018');
insert into product(id,name,price,sale_price,sales_count,sale_date) values(2, 'Desktop','30300','37030','43','03-04-2018');
insert into product(id,name,price,sale_price,sales_count,sale_date) values(3, 'Tablet','39010','48700','145','04-04-2018');
insert into product(id,name,price,sale_price,sales_count,sale_date) values(4, 'Phone','15000','17505','251','05-04-2018');
insert into product(id,name,price,sale_price,sales_count,sale_date) values(5, 'Phone','18000','22080','178','05-04-2018');
insert into product(id,name,price,sale_price,sales_count,sale_date) values(6, 'Tablet','30500','34040','58','05-04-2018');
insert into product(id,name,price,sale_price,sales_count,sale_date) values(7, 'Adapter','2000','2500','68','06-04-2018');
insert into product(id,name,price,sale_price,sales_count,sale_date) values(8, 'TV','45871','55894','165','07-04-2018');

DataSource Configuration

To establish connection to database and to fetch data from or write data to database table you need to configure datasource in Spring framework. I am using annotation based or Java based datasource configuration.

For establishing conneecting to database, the first thing would be to put the database settings into file under classpath directory src/main/resources.


#disable schema generation from Hibernate

The Java based datasource configuration is given below. The file is automatically read by Spring Boot framework as it is under the classpath directory with standard naming convention.

Spring framework provides Environment to retrieve your configuration properties easily. The class is annotation with @Configuration to indicate it is used for configuration purpose.

The datasource requires entity manager factory and if you do not create it then Spring Boot will create one for you.

You need to let Spring know which package contains entity classes and which package contains Spring Data JPA repository interfaces. Spring Data JPA Repository is built-in API that provides functions for performing basic CRUD (Create, Read, Update and Delete) operations out of the box.


import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;

@EnableJpaRepositories(basePackages = "")
public class Config {

	private Environment environment;

	public DataSource dataSource() {
		DriverManagerDataSource ds = new DriverManagerDataSource();
		return ds;

	public EntityManagerFactory entityManagerFactory(DataSource dataSource) {
		HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();

		LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
		return factory.getObject();


Entity Class

The entity class maps the database table columns into your Java class attributes for the given table name using annotation @Table on the entity class.

The @Column annotation is used to map your Java field or attribute with corresponding table column name. If your java attribute and table column name are same then you don’t need to specify the name using @Column annotation.

To map primary key column you need to put @Id annotation. I am using generation type identity because I have the auto increment primary key for the table.


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Table(name = "product")
public class Product {

	@Column(name = "id")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;

	@Column(name = "name")
	private String name;

	@Column(name = "price")
	private Double price;

	@Column(name = "sale_price")
	private Double salePrice;

	@Column(name = "sales_count")
	private Integer salesCount;

	@Column(name = "sale_date")
	private String saleDate;

	// getters and setters



Here is the repository that extends Spring’s JpaRepository interface to get the maximum benefits from Spring framework.

You need to pass entity class type and primary key type when you are extending the JpaRepository. The type is here Product and the primary key type is Integer in the Product entity class.

I have not declared any method in this interface because I don’t need to. I am just going to fetch all records for generating excel file or report for the table data.




public interface ProductRepository extends JpaRepository<Product, Integer> {


REST Controller

I am creating Spring REST controller class wherein I am going to implement the PDF file download functionality.

I have auto-wired the repository in this class which is not a good practice but for the sake of simplicity for this example. You can read best practices in Spring application.

I have created an endpoint /report/product/ with GET http request for downloading the PDF report from MySQL database.

I have fetched all data from MySQL table using repository to write to ByteArrayOutputStream using pdf Document intance. I have not created any file that would be stored in your system or machine. Rather on the fly I am generating the PDF content and sending as an attachment which can be downloaded or saved in the client side.

I am creating a title or heading before writing the actual data from MySQL table to PDF output. Then I iterate through each object of the Product and write to the table in the PDF content.

Finally in the response I have set few headers, such as, media type for file, file name and content disposition (as attachment) to forcefully download the file instead of rendering the data onto browser.


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class ProductRestController {

	private ProductRepository repository;

	public ResponseEntity<Resource> generateExcelReport() throws IOException, DocumentException {
		List<Product> products = repository.findAll();

		Document document = new Document(PageSize.A4, 25, 25, 25, 25);

		ByteArrayOutputStream os = new ByteArrayOutputStream();

		PdfWriter.getInstance(document, os);;

		Paragraph title = new Paragraph("Sales Information for Products",
				FontFactory.getFont(FontFactory.HELVETICA, 14, Font.BOLD, new BaseColor(0, 255, 255)));


		PdfPTable table = new PdfPTable(6);

		PdfPCell c1 = new PdfPCell(new Phrase("Id"));

		PdfPCell c2 = new PdfPCell(new Phrase("Name"));

		PdfPCell c3 = new PdfPCell(new Phrase("Price"));

		PdfPCell c4 = new PdfPCell(new Phrase("Sale Price"));

		PdfPCell c5 = new PdfPCell(new Phrase("Sales Count"));

		PdfPCell c6 = new PdfPCell(new Phrase("Sale Date"));

		for (Product product : products) {


		ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());

		HttpHeaders headers = new HttpHeaders();
		headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
		headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=ProductPdfReport.pdf");

		ResponseEntity<Resource> response = new ResponseEntity<Resource>(new InputStreamResource(is), headers,

		return response;


Main Class

The purpose of having a class with main method and @SpringBootAppliation is to deploy the app into embedded Tomcat server which is by default shipped with Spring Boot framework.


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class SpringPdfReportApp {

	public static void main(String[] args) {, args);


Testing the Application

Once you run the above main class your application will start up on default port 8080. If you cannot use default port for some reasons then you can specify the one you want in file using the key/value pair server.port=<port number>.

As it is GET request so you would be able to call the REST API endpoint (http://localhost:8080/report/product/) directly from the browser.

Once you call the URL in the browser you will see a pdf file named ProductPdfReport.pdf is ready for the save. You can save it anywhere on your system and open it to see the output as shown in the following image:

download pdf file report from mysql database in spring

Source Code


Thanks for reading.

Related posts

Leave a Comment