SoFunction
Updated on 2025-03-02

Summary of five implementation methods for SpringBoot generating PDF

Generating PDF files in Spring Boot applications can be achieved in the following ways:

1. Use PDFBox library

PDFBox is an open source Java library used to process PDF documents. ‌It supports creating, reading and modifying PDF files. ‌In Spring Boot applications, ‌ PDF files can be generated through the PDFBox library. ‌Specific implementation includes creating a PDDocument object, adding a page, setting page content stream, setting fonts and sizes, displaying text, and finally saving and closing the document. ‌

1. Add dependencies

<dependency>
    <groupId></groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.24</version>
</dependency>

2. Use PDFBox API to create a read and edit PDF file

Here is a simple example showing how to create a PDF file using PDFBox and add some text:

import ;
import ;
import ;
import .PDType1Font;
import ;
public class PDFBoxExample {
    public static void main(String[] args) {
        try {
            // Create a PDF document            PDDocument document = new PDDocument();
            // Create a page            PDPage page = new PDPage();
            (page);
            // Create a content stream            PDPageContentStream contentStream = new PDPageContentStream(document, page);
            // Set font            (PDType1Font.HELVETICA_BOLD);
            // Add text to PDF page            ("PDFBox! This is a PDF document.");
            // Close content stream            ();
            // Save the document            ("");
            // Close the document            ();
        } catch (IOException e) {
            ();
        }
    }
}

2. Use ReportLab library

ReportLab is an open source PDF generation library that supports multiple programming languages, including Java and Python. ‌In Spring Boot applications, ‌ can implement PDF generation by integrating ReportLab library. ‌This requires adding ReportLab dependencies to the project's file. ‌

1. Add dependencies

<dependency>
    <groupId></groupId>
    <artifactId>reportlab</artifactId>
    <version>4.5.3</version>
</dependency>

2. Create a service to generate PDF

import ;
import ;
import ;
import ;
import ;
import ;
import ;
@Service
public class PdfGenerationService {
    public void generatePdf(String filePath) throws DocumentException, FileNotFoundException {
        Document document = new Document();
        (document, new FileOutputStream(filePath));
        ();
        (new Paragraph("Hello, ReportLab!"));
        ();
    }
}

3. Call the service in a controller to generate PDF

import ;
import ;
import ;
import ;
import ;
@RestController
public class PdfController {
    @Autowired
    private PdfGenerationService pdfGenerationService;
    @GetMapping("/generatePdf")
    public String generatePdf() {
        try {
            ("");
            return "PDF generated successfully";
        } catch (FileNotFoundException | DocumentException e) {
            ();
            return "Error generating PDF";
        }
    }
}

3. Use the iText library

iText is a popular PDF processing library that supports the creation, editing and extraction of PDF files. ‌In Spring Boot, ‌ can generate PDF files by integrating the iText library. ‌This requires adding iText dependencies to the file, and writing code to generate a PDF file, such as creating a Document object, adding content, and saving it as a PDF file. ‌

1. Add dependencies

<dependency>
    <groupId></groupId>
    <artifactId>itext7-core</artifactId>
    <version>7.1.9</version>
</dependency>

2. Create a service to generate PDF

import .*;
import .*;
import ;
import ;
import ;
@Service
public class PdfService {
    public void generatePdf(String dest) throws IOException {
        // Initialize PDF writer
        PdfWriter writer = new PdfWriter(dest);
        // Initialize PDF document
        PdfDocument pdf = new PdfDocument(writer);
        // Initialize document
        Document document = new Document(pdf);
        // Add content
        (new Paragraph("Hello, Spring Boot and iText7!"));
        // Close document
        ();
        ("PDF created successfully!");
    }
}

3. Create a controller to call the service to generate PDF

import ;
import ;
import ;
import ;
@RestController
public class PdfController {
    @Autowired
    private PdfService pdfService;
    @GetMapping("/generatePdf")
    public String generatePdf() {
        try {
            ("target/");
            return "PDF generated";
        } catch (IOException e) {
            ();
            return "Error generating PDF";
        }
    }
}

4. Use dynamic HTML conversion

Create a dynamic HTML file first, and then convert it to PDF using HTML to PDF tools or libraries. ‌This method is suitable for situations where PDFs need to be generated from HTML content. ‌This conversion can be implemented in Spring Boot applications, for example by saving HTML content as a file, and then converting it to PDF using external tools or libraries. ‌

In Spring Boot, you can use the OpenPDF library (an open source iText branch) to generate PDF files dynamically.

1. Add dependencies

<dependency>
    <groupId></groupId>
    <artifactId>openhtmltopdf-core</artifactId>
    <version>1.0.10</version>
</dependency>

2. Create a service to generate PDF

import ;
import ;
import ;
import ;
import ;
@Service
public class PdfService {
    public byte[] generatePdfFromHtml(String htmlContent) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PdfRendererBuilder builder = new PdfRendererBuilder();
        ();
        (htmlContent, null);
        (outputStream);
        ();
        return ();
    }
}

3. Create a controller to provide PDF file download

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@Controller
@RequestMapping("/pdf")
public class PdfController {
    @Autowired
    private PdfService pdfService;
    @GetMapping
    public ResponseEntity<byte[]> generatePdf() throws IOException {
        String htmlContent = "<html><body><h1>Hello, World!</h1></body></html>";
        byte[] pdfBytes = (htmlContent);
        HttpHeaders headers = new HttpHeaders();
        (MediaType.APPLICATION_PDF);
        ("Content-Disposition", "attachment; filename=");
        return new ResponseEntity<>(pdfBytes, headers, );
    }
}

5. Use itextpdf to generate dynamically based on templates

This approach is suitable for situations where PDFs need to be generated based on a specific template. ‌through the integration of the itextpdf library, ‌ PDF files containing information such as contract labels, contract parties, and signing time can be dynamically generated based on the contract template.

1. Add dependencies

<dependency>
    <groupId></groupId>
    <artifactId>itext7-core</artifactId>
    <version>7.1.9</version>
    <type>pom</type>
</dependency>

2. Create PDF documents

Create a PDF document and add some content:

import .*;
import .*;
import ;
public void createPdf(String dest) throws Exception {
    //Initialize PDF writer
    PdfWriter writer = new PdfWriter(dest);
    //Initialize PDF document
    PdfDocument pdf = new PdfDocument(writer);
    //Initialize document
    Document document = new Document(pdf);
    //Add paragraph to the document
    (new Paragraph("Hello, World!"));
    //Close document
    ();
    ("PDF Created");
}

3. Call the createPdf method

In your Spring Boot application, you can call the createPdf method wherever you need it to create a PDF document.

This is the end of this article about the summary of the implementation method of SpringBoot generation PDF. For more related content on SpringBoot generation PDF, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!