How to Export data to PDF in Spring Boot Application. In this article, we will understand How to Export data to PDF in Spring Boot Application.
In a web application, there can be a requirement where you want to export the data to a PDF file. Through this article, you will get a clear idea of How to Export data to PDF in the Spring Boot Application. Here, we will use the OpenPDF Java library to generate PDF. Now, let us create a simple example where we will export the data to PDF.
Export Data to PDF in Spring Boot
Create Project
Create a project using Spring Initializr. If you don’t know how to create a project using the same check this article https://codedec.com/tutorials/how-to-create-spring-boot-project-using-spring-initializr/
Import a Project
Now, it’s time to import the project into STS. Go to File > Import > Maven > Existing Maven Project > Next > Browse > Select the project > Finish. Now it will take time to import the project and will import all the dependencies in case you added.
Project Structure
Add the OpenPDF Dependency
<dependency> <groupId>com.github.librepdf</groupId> <artifactId>openpdf</artifactId> <version>1.3.8</version> </dependency>
Configure application. properties file
# change the port server.port=8889 #Database Configrations spring.datasource.url=jdbc:mysql://localhost:3306/db_demo spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=root spring.datasource.password=root spring.jpa.database-platform = org.hibernate.dialect.MySQL8Dialect spring.jpa.generate-ddl=true spring.jpa.hibernate.ddl-auto = update
Create a Model Class
Here, we will create a Model class called Vehicle.java. I have used the Lombok library to remove boilerplate code. Check this article to know about Lombok Lombok Tutorial.
package com.abc.demo.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Setter @Getter @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "pdf_vehicle") public class Vehicle { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private String vehicleName; private String modelName; private String brand; private String vehicleNo; }
Create Repository Interface
Now, we will create a Data Access Layer called VehicleRepository which will extend JPARepository.
package com.abc.demo.dao; import org.springframework.data.jpa.repository.JpaRepository; import com.abc.demo.model.Vehicle; public interface VehicleRepository extends JpaRepository<Vehicle, Long> { }
Create a Service Layer
In this layer, we will create a VehicleService class that will fetch all the lists of vehicles from the database.
package com.abc.demo.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.abc.demo.dao.VehicleRepository; import com.abc.demo.model.Vehicle; @Service public class VehicleService { @Autowired private VehicleRepository repository; public List<Vehicle> getAllUser(){ return repository.findAll(); } }
Create Utility class
Here, we will create a PDFGeneratorVehicle.java class that will export the data to the PDF document.
package com.abc.demo.dao.util; import java.awt.Color; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.abc.demo.model.Vehicle; 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.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfWriter; @Setter public class PDFGeneratorVehicle { private List<Vehicle> vehicleList; public void generate(HttpServletResponse response) throws DocumentException, IOException { // Create the Object of Document Document document = new Document(PageSize.A4); // get the document and write the response to output stream PdfWriter.getInstance(document, response.getOutputStream()); document.open(); // Add Font Font fontTiltle = FontFactory.getFont(FontFactory.TIMES_ROMAN); fontTiltle.setSize(20); // Create Object of Paragraph Paragraph paragraph = new Paragraph("Vehicle List", fontTiltle); paragraph.setAlignment(Paragraph.ALIGN_CENTER); // Add to the document document.add(paragraph); PdfPTable table = new PdfPTable(5); table.setWidthPercentage(100f); table.setWidths(new int[] { 1, 1, 3, 2, 4 }); table.setSpacingBefore(5); // Create Table Header PdfPCell cell = new PdfPCell(); cell.setBackgroundColor(Color.MAGENTA); cell.setPadding(5); // Add Font Font font = FontFactory.getFont(FontFactory.TIMES_ROMAN); font.setColor(Color.WHITE); cell.setPhrase(new Phrase("ID", font)); table.addCell(cell); cell.setPhrase(new Phrase("Vehicle Name", font)); table.addCell(cell); cell.setPhrase(new Phrase("Model Name", font)); table.addCell(cell); cell.setPhrase(new Phrase("Brand", font)); table.addCell(cell); cell.setPhrase(new Phrase("Vehicle Number", font)); table.addCell(cell); for (Vehicle vehicle : vehicleList) { table.addCell(String.valueOf(vehicle.getId())); table.addCell(vehicle.getVehicleName()); table.addCell(vehicle.getModelName()); table.addCell(vehicle.getBrand()); table.addCell(vehicle.getVehicleNo()); } // Add table to document document.add(table); document.close(); } }
- Inside generate() method, first create the object of Document class. Now, get the document and write a response to the output stream.
- Now, add a font to the document. Create the Object of Paragraph (It is a series of chunks & phrases). Now, add this paragraph to the document.
- Now Create a Table using PDFTable class with 5 columns. Add the font, width, and Phrases to the table.
- Now, iterate over the list and add it to the table. At last, add it to the document object.
Create Controller Class
Create a TestController to handle requests. The request for the web page will be handle by the handler methods in the controller
package com.abc.demo.ctl; 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.abc.demo.dao.util.PDFGeneratorVehicle; import com.abc.demo.model.Vehicle; import com.abc.demo.service.VehicleService; import com.lowagie.text.DocumentException; @Controller public class TestController { @Autowired private VehicleService vehicleService; @GetMapping("/pdf/vehicle") public void generator(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<Vehicle> vehicleList = vehicleService.getAllUser(); PDFGeneratorVehicle generetorUser = new PDFGeneratorVehicle(); generetorUser.setVehicleList(vehicleList); generetorUser.generate(response); } }
Here, we get the list of vehicles from the database and pass it to the PDFGeneratorVehicle class and hence called the generate() method.
Run the Application
package com.abc.demo; 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.abc.demo.dao.VehicleRepository; import com.abc.demo.model.Vehicle; @SpringBootApplication public class PdfGeneratorExampleUsingSbApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(PdfGeneratorExampleUsingSbApplication.class, args); } @Autowired private VehicleRepository repo; @Override public void run(String... args) throws Exception { // TODO Auto-generated method stub for (int i = 0; i < 23; i++) { Vehicle vehicle = new Vehicle(); vehicle.setVehicleName("Swift" + i); vehicle.setModelName("M1526" + i); vehicle.setBrand("Swift" + i); vehicle.setVehicleNo("MH-516515313" + i); repo.save(vehicle); } } }
Now, Run the Application class and Go to localhost:8889/pdf/vehicle and here you will see the PDF document is generated automatically.
In this way, you can generate PDF documents in a Spring Boot Application.