How to Export Data to PDF in Spring Boot Application

Related Articles

It is often necessary to export certain data from our web application to an external document. Here we describe how we can export data from our spring boot app to a PDF file.

We use OpenPDF Library for producing and exporting data to PDF from our application. This is an open source java library used to create and modify PDFs using Java.

Let’s start encoding:

Creating a spring boot project

Let’s start the example by creating a spring boot project. go to And create a spring boot project.

Once the project is created by the spring boot API above, import it into Eclipse or another preferred IDE.

If you are using Eclipse, go to Import in Eclipse IDE and select “Cisting Maven Projects” to import the project. However, for other IDEs, the steps should be similar.


Select the folder you downloaded from the Spring initializer API and finally, the project is imported into the IDE.

Set up OpenPDF in Spring Boot Project

Now we’ll add OpenPDF stone dependency In our project. Add the following dependency on your project’s pom.xml:


Continue configuring the app

We need to add the following properties to our file to set the H2 database in the application.

#H2 Database

Create Class Model

Here, we create a student status. The student contains ID, there, And section where is the ID Will act as a unique identifier for each student.

package com.example.openpdf.entity;

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

public class Student 

	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private long id;
	private String name;
	private String section;
	public long getId() 
		return id;
	public void setId(long id) = id;
	public String getName() 
		return name;
	public void setName(String name) = name;
	public String getSection() 
		return section;
	public void setSection(String section) 
		this.section = section;

Application of a reservoir layer

We will now create the database layer that will mediate between our data and service layers. To do this, we create an interface by expanding the JpaRepository interface. We will also go over our model rate in its type parameter.

package com.example.openpdf.repository;

import com.example.openpdf.entity.Student;

public interface StudentRepository extends JpaRepository<Student, Long>

Application of service layer

Let’s create ours StudentService class apply a service layer in our app. We will currently define only one method Find all students In ours StudentService status. It will read the Find everything Method of Student database That will bring back all the students on the list.

package com.example.openpdf.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.openpdf.entity.Student;
import com.example.openpdf.repository.StudentRepository;

public class StudentService 

	private StudentRepository repo;

	public List<Student> findAllStudents() 
		return repo.findAll();

    public void save(Student student);

Create a Utility class for creating a PDF using OpenPDF

We will create a new class that will handle PDF creation using the OpenPDF library.

package com.example.openpdf.util;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.example.openpdf.entity.Student;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.CMYKColor;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;

public class PDFGenerator 

	// List to hold all Students
	private List<Student> studentList;

	public void generate(HttpServletResponse response) throws DocumentException, IOException 

		// Creating the Object of Document
		Document document = new Document(PageSize.A4);

		// Getting instance of PdfWriter
		PdfWriter.getInstance(document, response.getOutputStream());

		// Opening the created document to modify it;

		// Creating font
		// Setting font style and size
		Font fontTiltle = FontFactory.getFont(FontFactory.TIMES_ROMAN);

		// Creating paragraph
		Paragraph paragraph = new Paragraph("List Of Students", fontTiltle);

		// Aligning the paragraph in document

		// Adding the created paragraph in document

		// Creating a table of 3 columns
		PdfPTable table = new PdfPTable(3);

		// Setting width of table, its columns and spacing
		table.setWidths(new int[]  3, 3, 3 );

		// Create Table Cells for table header
		PdfPCell cell = new PdfPCell();

		// Setting the background color and padding

		// Creating font
		// Setting font style and size
		Font font = FontFactory.getFont(FontFactory.TIMES_ROMAN);

		// Adding headings in the created table cell/ header
		// Adding Cell to table
		cell.setPhrase(new Phrase("ID", font));
		cell.setPhrase(new Phrase("Student Name", font));
		cell.setPhrase(new Phrase("Section", font));

		// Iterating over the list of students
		for (Student student : studentList) 
			// Adding student id
			// Adding student name
			// Adding student section
		// Adding the created table to document

		// Closing the document


The code above is obvious with all the comments. However, let us explain once again some key points.

  • First, we create the document by defining the page size of the document. We do this through document status.
  • Then, we get the PdfWriter For example by providing the document created above and OutputStream.
  • Now, we need to create tables, paragraphs, headings, etc. Everything we need in our PDF document.
  • Finally, close the document.

Create a Class Controller

Finally, we will create our own cattle department to call ours PDFGeneration Service Department to create and export the data to a new PDF document.

package com.example.openpdf.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.example.openpdf.entity.Student;
import com.example.openpdf.service.StudentService;
import com.example.openpdf.util.PDFGenerator;
import com.lowagie.text.DocumentException;

public class StudentController 

	private StudentService service;
	public void generatePdf(HttpServletResponse response) throws DocumentException, IOException 
		DateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD:HH:MM:SS");
		String currentDateTime = dateFormat.format(new Date());
		String headerkey = "Content-Disposition";
		String headervalue = "attachment; filename=pdf_" + currentDateTime + ".pdf";
		response.setHeader(headerkey, headervalue);
		List<Student> studentList = service.findAllStudents();
		PDFGenerator generator = new PDFGenerator();

Here, we set headlines in ours HttpServletResponse And define the list of students in PDFGenerator status. It will generate the PDF and export it.

Check out the app

To test the app, you can apply an end form to create students or simply test the PDF export functionality by using CommandLineRunner.

To do this, apply CommandLineRunner In the main application department of Spring Boot.

package com.example.openpdf;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;

import com.example.openpdf.entity.Student;
import com.example.openpdf.service.StudentService;

public class OpenpdfApplication implements CommandLineRunner 

	public StudentService service;

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

	public void run(String... args) throws Exception 
		for (int i = 0; i < 11; i++) 
			Student student = new Student();
			student.setName("Student " + i);
			student.setSection("Section " + i);;



This is our PDF created. However, check out your app and see for yourself.



In this tutorial, we learned how to create PDFs using the OpenPDF library. Also, how can we export data from the Spring Boot app to PDF documents.



Please enter your comment!
Please enter your name here

Popular Articles