How you can Export Information to PDF in Spring Boot Software


It’s usually wanted that we export some information from our internet software to an exterior doc. Right here, we’re describing how we will export information from our spring boot software to a PDF file.

We’re utilizing the OpenPDF library for producing and exporting information to the PDF from our software. It’s an open-source java library used for creating and modifying PDF information utilizing Java.

Let’s begin coding:

Creating Spring Boot Challenge

Let’s begin the instance by making a spring boot undertaking. Go to begin.spring.io and generate a spring boot undertaking.

openpdf-example-springboot

As soon as the undertaking is created by the above spring initializer API then import it into Eclipse or different most well-liked IDE.

If utilizing Eclipse, Go to import in Eclipse IDE and choose the choice “Current Maven Initiatives” to import the undertaking. Nonetheless, for different IDEs, steps needs to be related.

import-openpdf-in-maven

Choose the downloaded folder from Spring initializer API and at last, the undertaking is imported into the IDE.

Configure OpenPDF in Spring Boot Challenge

We are going to now add OpenPDF maven dependency in our undertaking. Add the next dependency in pom.xml of your undertaking:

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

Continued Software Configuration

We have to add the next properties in our software.properties file to configure the H2 database within the software.

#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 Mannequin Class

Right here, we’re making a Pupil class. The Pupil comprises an id, title, and part the place the id will act as a singular identifier for each Pupil.

package deal com.instance.openpdf.entity;

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

@Entity
public class Pupil {

	@GeneratedValue(technique = GenerationType.IDENTITY)
	@Id
	personal lengthy id;
	personal String title;
	personal String part;
	
	public lengthy getId() {
		return id;
	}
	public void setId(lengthy id) {
		this.id = id;
	}
	public String getName() {
		return title;
	}
	public void setName(String title) {
		this.title = title;
	}
	public String getSection() {
		return part;
	}
	public void setSection(String part) {
		this.part = part;
	}
}

Implement Repository layer

We are going to now create the repository layer that can mediate between our Database and Service layers. For this, we’re creating an interface by extending the JpaRepository interface. We may also cross our mannequin class in its kind parameter.

package deal com.instance.openpdf.repository;

import org.springframework.information.jpa.repository.JpaRepository;
import com.instance.openpdf.entity.Pupil;

public interface StudentRepository extends JpaRepository<Pupil, Lengthy>{
}

Implement Service Layer

Let’s create our StudentService class to implement a service layer in our software. We are going to presently outline just one technique findAllStudents in our StudentService class. This can name the findAll technique of StudentRepository that can return all the scholars in an inventory.

package deal com.instance.openpdf.service;

import java.util.Record;
import org.springframework.beans.manufacturing unit.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.instance.openpdf.entity.Pupil;
import com.instance.openpdf.repository.StudentRepository;

@Service
public class StudentService {

	@Autowired
	personal StudentRepository repo;

	public Record<Pupil> findAllStudents() {
		return repo.findAll();
	}

    public void save(Pupil pupil) {
		repo.save(pupil);
	}
}

Create Utility class to generate PDF utilizing OpenPDF

We are going to create a brand new class that can deal with the PDF technology utilizing the OpenPDF library.

package deal com.instance.openpdf.util;

import java.io.IOException;
import java.util.Record;

import javax.servlet.http.HttpServletResponse;

import com.instance.openpdf.entity.Pupil;
import com.lowagie.textual content.Doc;
import com.lowagie.textual content.DocumentException;
import com.lowagie.textual content.Font;
import com.lowagie.textual content.FontFactory;
import com.lowagie.textual content.PageSize;
import com.lowagie.textual content.Paragraph;
import com.lowagie.textual content.Phrase;
import com.lowagie.textual content.pdf.CMYKColor;
import com.lowagie.textual content.pdf.PdfPCell;
import com.lowagie.textual content.pdf.PdfPTable;
import com.lowagie.textual content.pdf.PdfWriter;

public class PDFGenerator {

	// Record to carry all College students
	personal Record<Pupil> studentList;

	public void generate(HttpServletResponse response) throws DocumentException, IOException {

		// Creating the Object of Doc
		Doc doc = new Doc(PageSize.A4);

		// Getting occasion of PdfWriter
		PdfWriter.getInstance(doc, response.getOutputStream());

		// Opening the created doc to change it
		doc.open();

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

		// Creating paragraph
		Paragraph paragraph = new Paragraph("Record Of College students", fontTiltle);

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

		// Including the created paragraph in doc
		doc.add(paragraph);

		// Making a desk of three columns
		PdfPTable desk = new PdfPTable(3);

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

		// Create Desk Cells for desk header
		PdfPCell cell = new PdfPCell();

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

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

		// Including headings within the created desk cell/ header
		// Including Cell to desk
		cell.setPhrase(new Phrase("ID", font));
		desk.addCell(cell);
		cell.setPhrase(new Phrase("Pupil Title", font));
		desk.addCell(cell);
		cell.setPhrase(new Phrase("Part", font));
		desk.addCell(cell);

		// Iterating over the checklist of scholars
		for (Pupil pupil : studentList) {
			// Including pupil id
			desk.addCell(String.valueOf(pupil.getId()));
			// Including pupil title
			desk.addCell(pupil.getName());
			// Including pupil part
			desk.addCell(pupil.getSection());
		}
		// Including the created desk to doc
		doc.add(desk);

		// Closing the doc
		doc.shut();

	}
}

The code above is self-explanatory with all of the feedback. Nonetheless, let’s clarify some details another time.

  • First, we create the doc by defining the web page measurement of the doc. We do that through the use of Doc class.
  • Then, we get the PdfWriter occasion by offering the above-created doc and OutputStream.
  • Now, we have to create tables, paragraphs, headings, and so on. No matter we want in our PDF doc.
  • Lastly, shut the doc.

Create Controller class

Lastly, we are going to create our controller class that can name our PDFGeneration utility class to generate and export the information into a brand new PDF doc.

package deal com.instance.openpdf.controller;

import java.io.IOException;
import java.textual content.DateFormat;
import java.textual content.SimpleDateFormat;
import java.util.Date;
import java.util.Record;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.manufacturing unit.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.instance.openpdf.entity.Pupil;
import com.instance.openpdf.service.StudentService;
import com.instance.openpdf.util.PDFGenerator;
import com.lowagie.textual content.DocumentException;

@Controller
public class StudentController {

	@Autowired
	personal StudentService service;
  
    @GetMapping("/pdf/college students")
	public void generatePdf(HttpServletResponse response) throws DocumentException, IOException {
		
		response.setContentType("software/pdf");
		DateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD:HH:MM:SS");
		String currentDateTime = dateFormat.format(new Date());
		String headerkey = "Content material-Disposition";
		String headervalue = "attachment; filename=pdf_" + currentDateTime + ".pdf";
		response.setHeader(headerkey, headervalue);
		
		Record<Pupil> studentList = service.findAllStudents();
		
		PDFGenerator generator = new PDFGenerator();
		generator.setStudentList(studentList);
		generator.generate(response);
		
	}
}

Right here, we’re setting headers in our HttpServletResponse and setting the scholar checklist within the PDFGenerator class. This can generate the pdf and export it.

Take a look at the Software

To check the applying, you’ll be able to implement a front-end kind to create college students or just check the pdf export performance by making use of CommandLineRunner.

To do that, implement CommandLineRunner in your Spring Boot predominant software class.

package deal com.instance.openpdf;

import org.springframework.beans.manufacturing unit.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.internet.bind.annotation.GetMapping;

import com.instance.openpdf.entity.Pupil;
import com.instance.openpdf.service.StudentService;

@SpringBootApplication
public class OpenpdfApplication implements CommandLineRunner {

	@Autowired
	public StudentService service;

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

	@Override
	public void run(String... args) throws Exception {
		for (int i = 0; i < 11; i++) {
			Pupil pupil = new Pupil();
			pupil.setName("Pupil " + i);
			pupil.setSection("Part " + i);
			service.save(pupil);
		}

	}

}

Outcomes

That is our generated PDF. Nonetheless, check your personal software and see for your self.

results

Conclusion

On this tutorial, we realized how we will create PDFs utilizing the OpenPDF library. Additionally, how we will export information from the Spring Boot software to PDF paperwork.



Source_link

Leave a Reply

Your email address will not be published.