Date:

Share:

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 start.spring.io 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.

import-openpdf-in-maven

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:

<dependency>
    <groupId>com.github.librepdf</groupId>
    <artifactId>openpdf</artifactId>
    <version>1.3.26</version>
</dependency>

Continue configuring the app

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

#H2 Database
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=admin
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

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;

@Entity
public class Student 

	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Id
	private long id;
	private String name;
	private String section;
	
	public long getId() 
		return id;
	
	public void setId(long id) 
		this.id = id;
	
	public String getName() 
		return name;
	
	public void setName(String name) 
		this.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 org.springframework.data.jpa.repository.JpaRepository;
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;

@Service
public class StudentService 

	@Autowired
	private StudentRepository repo;

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

    public void save(Student student) 
		repo.save(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.io.IOException;
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
		document.open();

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

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

		// Aligning the paragraph in document
		paragraph.setAlignment(Paragraph.ALIGN_CENTER);

		// Adding the created paragraph in document
		document.add(paragraph);

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

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

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

		// Setting the background color and padding
		cell.setBackgroundColor(CMYKColor.MAGENTA);
		cell.setPadding(5);

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

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

		// Iterating over the list of students
		for (Student student : studentList) 
			// Adding student id
			table.addCell(String.valueOf(student.getId()));
			// Adding student name
			table.addCell(student.getName());
			// Adding student section
			table.addCell(student.getSection());
		
		// Adding the created table to document
		document.add(table);

		// Closing the document
		document.close();

	

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.io.IOException;
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;

@Controller
public class StudentController 

	@Autowired
	private StudentService service;
  
    @GetMapping("/pdf/students")
	public void generatePdf(HttpServletResponse response) throws DocumentException, IOException 
		
		response.setContentType("application/pdf");
		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();
		generator.setStudentList(studentList);
		generator.generate(response);
		
	

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;

@SpringBootApplication
public class OpenpdfApplication implements CommandLineRunner 

	@Autowired
	public StudentService service;

	public static void main(String[] args) 
		SpringApplication.run(OpenpdfApplication.class, args);
	

	@Override
	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);
			service.save(student);
		

	



Results

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

Results

Summary

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.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles