springjava.com
  • Core Java
  • Spring Core
  • Spring Boot
  • Spring MVC
  • Angular Tutorial

Related Posts

  • Spring Boot Annotations How to Upload a File in Spring Boot JSP How to create a Spring Boot project in VS Code How to create a Spring Boot project in IntelliJ IDEA How to create a Spring Boot project in STS How to Create and Setup Spring Boot Project in Eclipse Spring Boot CRUD Operations with JSP Spring Boot Pagination & Sorting with REST API Spring Boot CRUD with Thymeleaf Sending Mail Using Gmail SMTP Server In Spring Boot
Spring Boot

Export Data into PDF file in Spring Boot

Last Updated: 15-04-2022 Springjava

In this example, we can export data into a PDF file from the H2 Database. To achieve this task we can use the OpenPDF library.

Configuring OpenPDF library

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

configuring_openPDF_library

Table of content:

  1. Keep eclipse IDE ready
  2. Create a Spring Boot Starter Project for the example of exporting data to pdf(Select Spring Web, Spring Data JPA, and H2 Database dependencies)
  3. Define Database Connection in application.properties
  4. Create Entity class
  5. Create a Repository
  6. Create Service
  7. Create a Pdf File Generator class
  8. Create a Controller class
  9. Create a view page on the static folder of this exporting data to the pdf application
  10. Create CommandLineRunner on SpringBootApplication class
  11. Run the Project

1. Keep eclipse IDE ready
2. Create a Spring Boot Starter Project for the example of exporting data to pdf(Select Spring Web, Spring Data JPA, and H2 Database dependencies)

export_pdf_in_spring_boot

Maven Dependency

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>

<groupId>com.example</groupId>
<artifactId>Export_PDF_Spring_Boot_Example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Export_PDF_Spring_Boot_Example</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>11</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

3. Define Database Connection in application.properties

#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
spring.h2.console.enabled=true
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto= update
server.port=8888
server.servlet.context-path= /demo

4. Create Entity class

Student.java

package com.example.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Student {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;
  private String studentName;
  private String email;
  private String mobileNo;

  public Student() {
  }

  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getStudentName() {
    return studentName;
  }

  public void setStudentName(String studentName) {
    this.studentName = studentName;
  }

  public String getEmail() {
    return email;
  }

  public void setEmail(String email) {
    this.email = email;
  }

  public String getMobileNo() {
    return mobileNo;
  }

  public void setMobileNo(String mobileNo) {
    this.mobileNo = mobileNo;
  }
}

5. Create a Repository

StudentRepository.java

package com.example.repo;

import org.springframework.data.jpa.repository.JpaRepository;
import com.example.entity.Student;
public interface StudentRepoPDF extends JpaRepository<Student, Long> {}

6. Create Service

StudentService.java

package com.example.service;
import java.util.List;
import com.example.entity.Student;

public interface StudentService {
void addStudent(Student student);
List<Student> getStudentList();
}

StudentServiceImpl.java

package com.example.service;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.entity.Student;
import com.example.repo.StudentRepoPDF;

@Service
public class StudentServiceImpl implements StudentService {

@Autowired
StudentRepoPDF studentRepo;

@Override
public void addStudent(Student student) {
studentRepo.save(student);
}

@Override
public List<Student> getStudentList() {
return studentRepo.findAll();
}
}

7. Create a Pdf File Generator class

PdfGenerator.java

package com.example.util;

import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.example.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 {
public void generate(List < Student > studentList, 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 change it
    document.open();
    // Creating font
    // Setting font style and size
    Font fontTiltle = FontFactory.getFont(FontFactory.TIMES_ROMAN);
    fontTiltle.setSize(20);
    // Creating paragraph
    Paragraph paragraph1 = new Paragraph("List of the Students", fontTiltle);
    // Aligning the paragraph in the document
    paragraph1.setAlignment(Paragraph.ALIGN_CENTER);
    // Adding the created paragraph in the document
    document.add(paragraph1);
    // Creating a table of the 4 columns
    PdfPTable table = new PdfPTable(4);
    // Setting width of the table, its columns and spacing
    table.setWidthPercentage(100 f);
    table.setWidths(new int[] {3,3,3,3});
    table.setSpacingBefore(5);
    // Create Table Cells for the table header
    PdfPCell cell = new PdfPCell();
    // Setting the background color and padding of the table cell
    cell.setBackgroundColor(CMYKColor.BLUE);
    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 or  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("Email", font));
    table.addCell(cell);
    cell.setPhrase(new Phrase("Mobile No", font));
    table.addCell(cell);
    // Iterating the list of students
    for (Student student: studentList) {
      // Adding student id
      table.addCell(String.valueOf(student.getId()));
      // Adding student name
      table.addCell(student.getStudentName());
      // Adding student email
      table.addCell(student.getEmail());
      // Adding student mobile
      table.addCell(student.getMobileNo());
    }
    // Adding the created table to the document
    document.add(table);
    // Closing the document
    document.close();
  }
}

→ We can create a document by the defining page size of the document through the Document class.

→ We are getting a PdfWriter instance by providing the created document and OutputStream.

→ Creating paragraphs, tables, headings etc.

8. Create a Controller class

StudentController.java

package com.example.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 org.springframework.web.bind.annotation.GetMapping;
import com.example.entity.Student;
import com.example.service.StudentService;
import com.example.util.PdfGenerator;
import com.lowagie.text.DocumentException;

@Controller
public class StudentController {
  @Autowired
  private StudentService studentService;
  @GetMapping("/export-to-pdf")
  public void generatePdfFile(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=student" + currentDateTime + ".pdf";
    response.setHeader(headerkey, headervalue);
    List < Student > listofStudents = studentService.getStudentList();
    PdfGenerator generator = new PdfGenerator();
    generator.generate(listofStudents, response);
  }
}

9.  Create a view page on the static folder of this exporting data to pdf application

index.html

<!DOCTYPE html>
<html>
<head>
<title>Export PDF File</title>
</head>
<body class="container">
<p>Click the button for export PDF file.</p>
<a href="http://localhost:8888/demo/export-to-pdf" class="btn btn-primary">Download PDF File</a>
</body>
</html>

10. Create CommandLineRunner on SpringBootApplication class

package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.entity.Student;
import com.example.service.StudentService;

@SpringBootApplication
public class ExportPdfSpringBootExampleApplication implements CommandLineRunner {
  @Autowired
  private StudentService studentService;
  public static void main(String[] args) {
    SpringApplication.run(ExportPdfSpringBootExampleApplication.class, args);
  }
  @Override
  public void run(String...a) {
    for (int i = 0; i <= 10; i++) {
      Student student = new Student();
      student.setStudentName("Student Name");
      student.setEmail("student@mail.com");
      student.setMobileNo("XXXXXXXXXX");
      studentService.addStudent(student);
    }
  }
}

11. Run the Project

RightClick on SpringBootApplication class(ExportPdfSpringBootExampleApplication) then click on Run as Java Application. To check the database console. We can type this URL on the browser "http://localhost:8888/demo/h2-console/" for testing this example of whether the application created a table on the H2 database and whether data is inserted properly or not.

export_pdf_in_spring_boot

export_pdf_in_spring_boot

To check we can type this URL on our browser "http://localhost:8888/demo/" for testing if this application is properly exporting data to pdf.

export_pdf_in_spring_boot

Click on the  Download PDF File link to download the pdf file.

export_pdf_in_spring_boot

Conclusion

This example is explained:
• How to transform data into a pdf file from a database?
• How to use the openPDF library?

What is Spring Boot How to Create a Spring Boot Project in IDE Spring MVC with Spring Boot Configure

Leave your thought here

Your email address will not be published. Required fields are marked *

springjava_com
  • springjavateam@gmail.com
  • springjava.com
Learn
    • Core Java
    • Spring Core
    • Spring Boot
    • Spring MVC
    • Angular Tutorial
Quick links
  • About Us
  • Contact Us
  • Privacy Policy
Subscribe to Blog via Email
Subscribe
© 2021 Spring Java. All Rights Reserved.
springjava.com
  • Core Java
  • Spring Core
  • Spring Boot
  • Spring MVC
  • Angular Tutorial
  • About Us
  • Contact Us