How to Generate PDFs In Spring Boot?

18 minutes read

To generate PDFs in Spring Boot, you can follow these steps:

  1. Add the necessary dependencies: Include the required dependencies in your Maven or Gradle build file. Typically, you need the spring-boot-starter-web and spring-boot-starter-thymeleaf dependencies.
  2. Create the PDF template: Design a Thymeleaf template for your PDF. You can define the layout, content, and styling of the PDF using HTML and CSS.
  3. Configure the PDF generator: Create a PDF generator class that will convert the Thymeleaf template into a PDF. You can use libraries like iText, Flying Saucer, or Apache PDFBox for this purpose.
  4. Implement the PDF generation endpoint: In your Spring Boot application, create a controller with an HTTP endpoint that triggers the generation of the PDF. This endpoint should take any required input data and pass it to the PDF generator.
  5. Render the PDF template: Within the controller, pass the necessary data to the Thymeleaf template and render it using the PDF generator. This will create a PDF file based on the template and data.
  6. Serve the generated PDF: Return the generated PDF as a response to the client. You can set the appropriate headers like Content-Type and Content-Disposition to ensure that the PDF is downloaded or displayed correctly in the browser.
  7. Test the PDF generation: Verify that your PDF generation is working as expected. You can test it by accessing the PDF generation endpoint and checking the downloaded PDF file or viewing it in the browser.


By following these steps, you can easily generate PDFs in Spring Boot applications.

Best Spring Boot Books to Read in May 2024

1
Full Stack Development with Spring Boot and React: Build modern and scalable web applications using the power of Java and React, 3rd Edition

Rating is 5 out of 5

Full Stack Development with Spring Boot and React: Build modern and scalable web applications using the power of Java and React, 3rd Edition

2
Spring Boot Persistence Best Practices: Optimize Java Persistence Performance in Spring Boot Applications

Rating is 4.9 out of 5

Spring Boot Persistence Best Practices: Optimize Java Persistence Performance in Spring Boot Applications

3
Spring Boot in Action

Rating is 4.8 out of 5

Spring Boot in Action

4
Spring Boot: Up and Running: Building Cloud Native Java and Kotlin Applications

Rating is 4.7 out of 5

Spring Boot: Up and Running: Building Cloud Native Java and Kotlin Applications

5
Learning Spring Boot 3.0: Simplify the development of production-grade applications using Java and Spring, 3rd Edition

Rating is 4.6 out of 5

Learning Spring Boot 3.0: Simplify the development of production-grade applications using Java and Spring, 3rd Edition

6
Spring in Action, Sixth Edition

Rating is 4.5 out of 5

Spring in Action, Sixth Edition

7
Modern API Development with Spring and Spring Boot: Design highly scalable and maintainable APIs with REST, gRPC, GraphQL, and the reactive paradigm

Rating is 4.4 out of 5

Modern API Development with Spring and Spring Boot: Design highly scalable and maintainable APIs with REST, gRPC, GraphQL, and the reactive paradigm

8
Spring Boot and Angular: Hands-on full stack web development with Java, Spring, and Angular

Rating is 4.3 out of 5

Spring Boot and Angular: Hands-on full stack web development with Java, Spring, and Angular


How can I generate PDFs with multiple language support in Spring Boot?

To generate PDFs with multiple language support in Spring Boot, you can follow these steps:

  1. Add the required dependencies to your Spring Boot project. You will need the following dependencies: Spring Boot Starter Web: for handling HTTP requests and responses. Apache PDFBox: for generating PDF documents. iText PDF: for manipulating PDF documents.
  2. Configure your project to use these dependencies. You can do this by adding the corresponding dependencies to your pom.xml file or build.gradle file.
  3. Create a controller class that will handle the PDF generation request. Annotate the controller class with @RestController or @Controller annotation.
  4. Inside the controller class, create a method that will handle the PDF generation request. Annotate the method with @RequestMapping or @GetMapping annotation to specify the URL mapping.
  5. Use PdfDocument or PdfWriter class from Apache PDFBox or iText PDF library to create a new PDF document. Set the document's properties such as title, author, and subject.
  6. Use PDFFont or Font class to specify the font and size to be used for the text in the PDF document. Set the font encoding to support multiple languages.
  7. Add the desired text to the PDF document using PDPageContentStream or PdfContentByte class. Specify the coordinates and position of the text within the document.
  8. Close the PDF document using the close method to save the document.
  9. Return the generated PDF file back in the response. You can use ResponseEntity or HttpServletResponse class to achieve this.


Here's an example code snippet that generates a PDF with multiple language support using Apache PDFBox:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@RestController
public class PdfController {

   @GetMapping("/generate-pdf")
   public ResponseEntity<ByteArrayResource> generatePdf() throws IOException {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      PDDocument document = new PDDocument();
      
      // Set document properties
      document.getDocumentInformation().setTitle("Generated PDF with Multiple Language Support");
      document.getDocumentInformation().setAuthor("Your Name");
      document.getDocumentInformation().setSubject("PDF with multi-language");
      
      // Set font and size for text
      PDFont font = PDType1Font.HELVETICA;
      float fontSize = 12;
      
      PDPage page = new PDPage();
      document.addPage(page);
      
      // Create a new page and content stream.
      PDPageContentStream contentStream = new PDPageContentStream(document, page);
      
      // Add text to the PDF document
      contentStream.setFont(font, fontSize);
      contentStream.beginText();
      contentStream.newLineAtOffset(100, 700);
      
      // Add text in different languages
      contentStream.showText("Hello"); // English
      contentStream.showText("مرحبا"); // Arabic
      contentStream.showText("你好"); // Chinese
      
      contentStream.endText();
      contentStream.close();
      
      // Save the document
      document.save(baos);
      document.close();
      
      // Set the response headers
      HttpHeaders headers = new HttpHeaders();
      headers.add("Content-Disposition", "attachment; filename=generated.pdf");
      
      // Return the generated PDF file in the response
      return ResponseEntity.ok()
            .headers(headers)
            .contentType(MediaType.APPLICATION_PDF)
            .body(new ByteArrayResource(baos.toByteArray()));
   }
}


Note: This is just an example to demonstrate the concept. You may need to modify it based on your specific requirements and dependencies.


Can I generate PDF documents from HTML content in Spring Boot?

Yes, you can generate PDF documents from HTML content in Spring Boot. There are several libraries and tools available that can help you achieve this. One popular option is using the Flying Saucer library, which is a Java library that converts XHTML to PDF using the iText library.


Here is an example of generating a PDF document from HTML content using Flying Saucer in Spring Boot:

  1. Add the following dependencies to your pom.xml file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<dependency>
  <groupId>org.xhtmlrenderer</groupId>
  <artifactId>flying-saucer-pdf</artifactId>
  <version>9.1.22</version>
</dependency>
<dependency>
  <groupId>com.lowagie</groupId>
  <artifactId>itext</artifactId>
  <version>2.1.7</version>
</dependency>


  1. Create a service class that generates the PDF document:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.springframework.stereotype.Service;
import java.io.FileOutputStream;
import java.io.OutputStream;

@Service
public class PdfGeneratorService {

    public void generatePdfFromHtml(String htmlContent, String outputFilePath) throws Exception {
        OutputStream outputStream = new FileOutputStream(outputFilePath);
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(htmlContent);
        renderer.layout();
        renderer.createPDF(outputStream);
        outputStream.close();
    }
}


  1. Use the PdfGeneratorService in your controller to generate the PDF document:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import java.io.File;

@RestController
public class PdfController {

    @Autowired
    private PdfGeneratorService pdfGeneratorService;

    @GetMapping("/generate-pdf")
    public String generatePdf() throws Exception {
        File htmlFile = ResourceUtils.getFile("classpath:templates/my-template.html");
        String htmlContent = new String(java.nio.file.Files.readAllBytes(htmlFile.toPath()), "UTF-8");

        String outputFilePath = "path/to/output/file.pdf";
        pdfGeneratorService.generatePdfFromHtml(htmlContent, outputFilePath);

        return "PDF generated successfully!";
    }
}


In this example, we assume you have an HTML template file called my-template.html placed under the templates directory in your Spring Boot project. You can modify the paths and contents according to your needs.


By accessing the /generate-pdf endpoint, the PDF document will be generated and saved to the specified path (path/to/output/file.pdf in this example).


What are the alternatives to PDF for generating printable documents in Spring Boot?

There are several alternatives to PDF for generating printable documents in Spring Boot. Some of them include:

  1. HTML/CSS: Instead of generating PDF directly, you can generate HTML/CSS templates and use a library like Thymeleaf or FreeMarker to generate printable documents. These templates can be easily converted to PDF format using libraries like Flying Saucer or iText.
  2. Excel: If your printable documents involve tabular data or spreadsheets, you can generate them in Excel format using libraries like Apache POI or JExcelApi. These libraries allow you to create Excel templates with custom styling and populate data dynamically.
  3. Word: For generating printable documents in Word format, you can use libraries like Apache POI or Docx4j. These libraries provide APIs to create Word templates with formatted text, tables, images, etc., and populate them with data.
  4. CSV: If your printable documents are simple and involve only tabular data, you can generate them in CSV (Comma-Separated Values) format. CSV files can be easily opened in spreadsheet applications like Excel and printed.
  5. Image: In some cases, generating printable documents as images might be suitable. You can use libraries like Java2D or Apache Batik to create images with custom graphics and text, which can then be printed.


It's important to consider the requirements and complexity of your printable documents when choosing an alternative to PDF.

Best Cloud Providers to Host Java Spring Boot in 2024

1
AWS

Rating is 5 out of 5

AWS

2
DigitalOcean

Rating is 4.9 out of 5

DigitalOcean

3
Vultr

Rating is 4.8 out of 5

Vultr

4
Cloudways

Rating is 4.7 out of 5

Cloudways


What is the role of Freemarker in generating PDFs in Spring Boot?

Freemarker is a template engine that allows generating dynamic content in various formats, including PDF. In the context of Spring Boot, Freemarker is often used together with libraries like Apache PDFBox or iText to generate PDFs.


The role of Freemarker in generating PDFs in Spring Boot involves the following steps:

  1. Templating: Freemarker provides a template that defines the structure of the PDF document. It allows defining placeholders that can be dynamically replaced with actual data during the generation process.
  2. Data retrieval: In Spring Boot, data required for the PDF generation can be retrieved from various sources like a database, REST APIs, or other services. This data is typically passed to the Freemarker template as a model object.
  3. Rendering: With the data and template in place, Freemarker merges the data with the template to produce an output document, often in HTML format.
  4. Conversion: The HTML output generated by Freemarker can then be converted to PDF using libraries like Apache PDFBox or iText. These libraries provide utilities to convert HTML to PDF by rendering the HTML and generating a corresponding PDF file.
  5. Delivery: The generated PDF can be delivered to the client or stored in a file system or database for later retrieval.


Overall, Freemarker plays a crucial role in defining the structure and content of PDFs generated in Spring Boot applications, allowing for dynamic generation of PDF documents based on provided data and templates.


Can I generate barcodes in the PDF generated by Spring Boot?

Yes, you can generate barcodes in the PDF generated by Spring Boot. There are several libraries available that can assist you in generating barcodes in a PDF using Spring Boot.


One popular library is the barcode4j library, which provides support for various barcode formats. You can integrate this library with Spring Boot by including the necessary dependencies in your project's pom.xml file.


Here's a step-by-step guide on how to generate barcodes in a PDF using barcode4j with Spring Boot:

  1. Add the barcode4j dependency to your pom.xml:
1
2
3
4
5
<dependency>
    <groupId>net.sf.barcode4j</groupId>
    <artifactId>barcode4j</artifactId>
    <version>2.1</version>
</dependency>


  1. Create a barcode generation service. This service will use the barcode4j library to generate a barcode image.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import org.krysalis.barcode4j.impl.qr.QRCodeBean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

@Service
public class BarcodeService {

    public byte[] generateBarcode(String barcodeText) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        BitmapCanvasProvider canvasProvider =
                new BitmapCanvasProvider(outputStream, "image/jpeg", 200, BufferedImage.TYPE_BYTE_BINARY, false, 0);

        QRCodeBean qrCodeBean = new QRCodeBean();
        qrCodeBean.generateBarcode(canvasProvider, barcodeText);

        canvasProvider.finish();

        return outputStream.toByteArray();
    }
}


  1. Create a controller that generates the PDF and includes the barcode image.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
@RestController
public class PdfController {

    @Autowired
    private BarcodeService barcodeService;

    @GetMapping("/generatePdf")
    public ResponseEntity<Resource> generatePdf() throws IOException, DocumentException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        document.open();

        // Generate barcode image
        byte[] barcodeImage = barcodeService.generateBarcode("Barcode Text");

        // Convert barcode image to iText Image object
        Image image = Image.getInstance(barcodeImage);

        // Add image to PDF
        document.add(image);

        document.close();
        writer.close();

        // Create a ByteArrayInputStream from the PDF byte array
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(outputStream.toByteArray());

        // Create a Resource that wraps the ByteArrayInputStream
        Resource resource = new InputStreamResource(byteArrayInputStream);

        // Return the PDF as a ResponseEntity with appropriate headers
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_TYPE, "application/pdf")
                .body(resource);
    }
}


In this example, the /generatePdf endpoint will generate a PDF containing a barcode image. You can modify the barcode generation service and controller code to suit your specific requirements and barcode format.


Remember to add the required annotations (@RestController, @Service, etc.) and configure any necessary endpoint mappings in your Spring Boot application.


How can I generate PDFs with complex layouts and styling in Spring Boot?

To generate PDFs with complex layouts and styling in Spring Boot, you can follow these steps:

  1. Add the required dependencies: implementation 'com.itextpdf:itextpdf:5.5.13' implementation 'org.xhtmlrenderer:flying-saucer-pdf:9.1.20'
  2. Create a template for your PDF using HTML and CSS. You can use Thymeleaf or any other templating engine to design the layout. Make sure to include the required CSS styles for complex styling.
  3. Create a method in your controller to generate the PDF. This method should take the template as input and convert it into a PDF using iText and Flying Saucer. @GetMapping("/pdf") public ResponseEntity generatePDF() throws IOException, DocumentException { // Load the HTML template ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver(); templateResolver.setPrefix("templates/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode("HTML5"); templateResolver.setCharacterEncoding("UTF-8"); TemplateEngine templateEngine = new TemplateEngine(); templateEngine.setTemplateResolver(templateResolver); String htmlContent = templateEngine.process("template", new Context()); // Generate PDF from HTML template ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); XMLWorkerHelper.getInstance().parseXHtml(writer, document, new ByteArrayInputStream(htmlContent.getBytes())); document.close(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_PDF); headers.setContentDispositionFormData("attachment", "my-pdf.pdf"); return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.OK); }
  4. Create an HTML template file in the resources/templates directory with the desired complex layout and styling. You can use HTML and CSS to design the layout.
  5. Configure the application to serve static resources from the resources/static directory by adding the following configuration to the application.properties file: spring.mvc.static-path-pattern=/resources/** spring.resources.static-locations=classpath:/static/
  6. Start the Spring Boot application and access the PDF generation endpoint (e.g., http://localhost:8080/pdf) to download the generated PDF.


By following these steps, you should be able to generate PDFs with complex layouts and styling in your Spring Boot application.


Which libraries can be used to generate PDFs in Spring Boot?

There are several libraries that can be used to generate PDFs in a Spring Boot application. Some popular options include:

  1. Apache PDFBox: An open-source Java library for creating and manipulating PDF documents.
  2. iText: A popular Java library for creating and manipulating PDF files.
  3. Flying Saucer: A library that converts XHTML to PDF using iText as the underlying PDF library.
  4. JasperReports: A reporting engine that can generate PDF documents based on XML template files.
  5. Thymeleaf PDF Extension: An extension library for Thymeleaf that can generate PDFs using Flying Saucer or iText.


These libraries can be easily integrated with Spring Boot to generate and serve PDF documents in a web application.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To integrate Spring Boot with Angular, the following steps can be followed:Create a new Spring Boot project: Start by setting up a new Spring Boot project using your preferred IDE or Spring Initializer. Include the necessary dependencies for web and data. Set ...
To connect Spring Boot to MySQL, you need to follow these steps:First, make sure you have MySQL installed and running on your system. In your Spring Boot project, open the application.properties file. Add the following properties to the file: spring.datasourc...
To stop a Spring Boot application from the command line, you need to perform the following steps:Identify the process ID (PID) of the running Spring Boot application. You can do this by using the jps command. Open the command prompt and type jps -l. Look for t...