SoFunction
Updated on 2025-04-07

Detailed explanation of four implementation methods for exporting PDF in SpringBoot

Implement PDF export function in Spring Boot application, and you can choose from a variety of libraries and technology stacks. Each method has its advantages and disadvantages and is suitable for different scenarios. Here are four common ways: iText, Apache PDFBox, JasperReports, and Thymeleaf + Flying Saucer. I will compare these methods in detail and provide corresponding code examples.

1. iText

advantage:

  • Rich API: Supports complex PDF operations, such as encryption, digital signature, form processing, etc.
  • Enterprise-level support: Provides a wide range of documentation and support communities.
  • Multi-format output: In addition to PDF, it also supports conversion of other formats (such as HTML and XML).

shortcoming:

  • Commercial License: iText 7 is commercial software, and certain advanced features require a license to be purchased.
  • Learning curve: The API is relatively complex and may require certain learning costs.

performance:

For most application scenarios, iText's performance is sufficient. It performs excellently in memory management and file processing speed, especially suitable for handling complex PDF documents.

Applicable scenarios:

Suitable for applications that require the generation of complex PDF documents, especially those involving security and advanced features.

Sample code:

<!-- Add dependencies -->
<dependency>
    <groupId></groupId>
    <artifactId>itext7-core</artifactId>
    <version>7.1.15</version> <!-- Please check and use the latest version -->
</dependency>
import ;
import ;
import ;
import ;

import ;
import ;

public class ITextPdfService {

    public void export(HttpServletResponse response) throws IOException {
        // Set response header        ("application/pdf");
        ("Content-Disposition", "attachment; filename=");

        try (PdfWriter writer = new PdfWriter(());
             PdfDocument pdf = new PdfDocument(writer);
             Document document = new Document(pdf)) {

            // Add content to PDF            (new Paragraph("Hello, this is a PDF document created with iText in Spring Boot!"));

            // Close the document            ();
        }
    }
}

2. Apache PDFBox

advantage:

  • Fully open source: No commercial restrictions, suitable for all types of projects.
  • Lightweight: fewer dependencies and simple project structure.
  • Easy to get started: The API is relatively simple and suitable for rapid development and learning.

shortcoming:

  • Limited Features: On some complex features, such as handling large PDFs or performing advanced operations, may not be as powerful as iText.
  • Performance issues: In handling very large files or high concurrency scenarios, performance may be slightly inferior to iText.

performance:

PDFBox performs well when processing smaller PDF files, but may perform slightly worse than iText when processing large files or high concurrency scenarios.

Applicable scenarios:

Suitable for applications that need to generate simple PDF documents, especially those that want to remain fully open source.

Sample code:

<!-- Add dependencies -->
<dependency>
    <groupId></groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.27</version> <!-- Please check and use the latest version -->
</dependency>
import ;
import ;
import ;
import .PDType1Font;

import ;
import ;

public class PdfBoxPdfService {

    public void export(HttpServletResponse response) throws IOException {
        // Set response header        ("application/pdf");
        ("Content-Disposition", "attachment; filename=");

        try (PDDocument document = new PDDocument()) {
            PDPage page = new PDPage();
            (page);

            try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
                (PDType1Font.HELVETICA_BOLD, 12);
                ();
                (100, 700);
                ("Hello, this is a PDF document created with Apache PDFBox in Spring Boot!");
                ();
            }

            // Write PDF to the response output stream            (());
        }
    }
}

3. JasperReports

advantage:

  • Strong report design capabilities: Supports complex tables, charts, groupings, subreports and other functions.
  • Multi-data source support: You can obtain data from database, JavaBean collection, CSV, XML and other data sources.
  • Rich styles and formatting: Supports a variety of style settings such as fonts, colors, borders, backgrounds, and formats such as dates and numbers.
  • High integration: Easy integration with Spring Boot, making it easy to embed report generation logic into your application.
  • Various output formats: In addition to PDF, it also supports multiple output formats such as HTML, Excel, CSV, etc.

shortcoming:

  • The learning curve is steeper: The syntax of JRXML templates is relatively complicated and takes some time to master it.
  • There are many dependencies: multiple dependencies need to be introduced, which may increase the complexity of the project.
  • Performance Issues: When dealing with very large data sets, you may encounter performance bottlenecks, especially in terms of memory management and rendering speed.

performance:

Performs better when dealing with complex reports and large data sets, especially when advanced features (such as grouping, charts).

Applicable scenarios:

Suitable for applications that need to generate complex reports, especially scenarios that contain a large number of data, charts, groups and other elements.

Suitable for applications that need to support multiple output formats.

Sample code:

<!-- Add dependencies -->
<dependency>
    <groupId></groupId>
    <artifactId>jasperreports</artifactId>
    <version>6.17.0</version> <!-- Please check and use the latest version -->
</dependency>
import .*;
import ;
import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;

@RestController
@RequestMapping("/api")
public class JasperReportController {

    @GetMapping("/export-jasper-pdf")
    public void export(HttpServletResponse response) throws Exception {
        // Set response header        ("application/pdf");
        ("Content-Disposition", "attachment; filename=");

        // Load the JRXML template        InputStream reportTemplate = getClass().getResourceAsStream("/templates/");
        JasperReport jasperReport = (reportTemplate);

        // Prepare data        List<User> users = (); // Suppose there is a UserService class        JRBeanCollectionDataSource dataSource = new JRBeanCollectionDataSource(users);

        // Set parameters        Map<String, Object> parameters = new HashMap<>();
        ("title", "User Report");

        // Generate PDF        JasperPrint jasperPrint = (jasperReport, parameters, dataSource);
        (jasperPrint, ());
    }
}

4. Thymeleaf + Flying Saucer

advantage:

  • HTML/CSS friendly: Use standard HTML and CSS for page layout and style settings, which is perfect for front-end developers.
  • Easy to maintain: HTML templates are easy to understand and modify, especially for teams who are already familiar with HTML/CSS.
  • High flexibility: It is easy to convert existing Thymeleaf templates to PDF, reducing duplicate work.
  • Lightweight: Compared with JasperReports, Flying Saucer has fewer dependencies and a simpler project structure.
  • Rapid development: For simple PDF generation needs, development speed is faster because there is no need to learn new template languages.

shortcoming:

  • Limited functions: Compared with JasperReports, Flying Saucer has limited functions, especially when processing complex reports (such as grouping and charts).
  • General performance: In handling large files or high concurrency scenarios, the performance may not be as good as JasperReports.
  • Style Compatibility: Some CSS styles may not be fully compatible, resulting in PDF rendering effects not matching expectations.

performance:

For simple PDF generation requirements, the performance is sufficient, the development speed is fast and the maintenance cost is low.

Applicable scenarios:

  • Suitable for applications that need to convert existing HTML pages to PDFs, especially those that already have ready-made HTML templates.
  • Suitable for generating simple documents, such as invoices, contracts, reports, etc., without involving complex reporting functions.

Sample code:

<!-- Add dependencies -->
<dependency>
    <groupId></groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.0.</version> <!-- Please check and use the latest version -->
</dependency>
<dependency>
    <groupId></groupId>
    <artifactId>flying-saucer-pdf-itext5</artifactId>
    <version>9.1.20</version> <!-- Please check and use the latest version -->
</dependency>
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;
import ;
import ;
import ;

@RestController
@RequestMapping("/api")
public class PdfController {

    private final TemplateEngine templateEngine;

    public PdfController(TemplateEngine templateEngine) {
         = templateEngine;
    }

    @GetMapping("/export-thymeleaf-pdf")
    public void export(HttpServletResponse response) throws Exception {
        // Set response header        ("application/pdf");
        ("Content-Disposition", "attachment; filename=");

        // Load HTML template        InputStream templateInputStream = new ClassPathResource("templates/").getInputStream();
        String htmlContent = new String((), StandardCharsets.UTF_8);

        // Prepare context data        Context context = new Context();
        ("users", ()); // Suppose there is a UserService class        ("title", "User Report");

        // Render HTML        String processedHtml = (htmlContent, context);

        // Convert HTML to PDF        ITextRenderer renderer = new ITextRenderer();
        (processedHtml);
        ();

        // Output PDF        try (OutputStream outputStream = ()) {
            (outputStream);
        }
    }
}

Comparison of performance and ease of use

iText Apache PDFBox JasperReports Thymeleaf + Flying Saucer
performance high middle High (complex report) Medium (simple document)
Ease of use complex Simple complex Simple
Function powerful limited Very powerful (report) Limited (HTML/CSS)
Dependencies More (some require commercial license) few More few
Applicable scenarios Complex PDF documents Simple PDF document Complex Reports Simple Document/HTML to PDF
Learning curve Steep gentle Steep gentle

Summarize

Choose iText if you need to generate complex PDF documents, especially enterprise-level applications involving security and advanced features. iText provides the most comprehensive features and optimal performance, but requires attention to its commercial licensing requirements.

Choose Apache PDFBox if you want to stay fully open source and just generate a simple PDF document. PDFBox is lightweight and easy to use, suitable for small projects or scenarios that require low performance.

Choose JasperReports If you need to generate complex reports, especially functions such as grouping, charts, subreports, etc. JasperReports is a powerful and mature tool suitable for enterprise-level applications.

Choose Thymeleaf + Flying Saucer If you need to convert an existing HTML page to a PDF, or just generate a simple document (such as invoices, contracts, etc.). It is easy to use and fast to develop, especially suitable for front-end developers.

In actual projects, it is recommended to select appropriate tools based on specific needs and technology stacks. If you are not sure which tool is better, try a small-scale prototype project first, evaluate its performance and ease of use before making a final decision.

The above is a detailed explanation of the four implementation methods of SpringBoot export PDF. For more information about SpringBoot export PDF, please pay attention to my other related articles!