Spring Boot Web Convert HTML String to PDF File

Tags: flying-saucer-pdf-openpdf Flying Saucer PDF HTML to PDF

In this Java Spring Boot tutorial we learn how to implement a Spring Boot web application which allow user input HTML content and they can convert the HTML content to PDF file and download it.

Table of contents

  1. Create New Spring Boot Web Application
  2. Add dependencies to the Spring Boot Web project
  3. Implement PDF Service to Convert HTML to PDF
  4. Implement Controller class and HTML view
  5. Complete Source Code and Run the Web Application
  6. Download The Source Code

Create New Spring Boot Web Application

Open IntelliJ IDEA, select the menu File > New > Project. (or click on New Project button at IntelliJ Welcome dialog)

On the New Project dialog, select Spring Initializr and click Next button.

Spring Boot Web Convert HTML String to PDF File

On the Spring Initializr Project Settings dialog input the new project information as below and click Next button.

  • Group: dev.simplesolution
  • Artifact: spring-boot-web-html-to-pdf
  • Type: Gradle
  • Language: Java
  • Version: 1.0.0
  • Name: spring-boot-web-html-to-pdf
  • Description: Spring Boot Web Convert HTML String to PDF File
  • Package: dev.simplesolution.springboothtmlpdf

Spring Boot Web Convert HTML String to PDF File

On the Dependencies dialog, select below dependencies and click Next button.

  • Spring Web
  • Thymeleaf

Spring Boot Web Convert HTML String to PDF File

Select the location for your project and click Finish button to create new Spring Boot project.

Spring Boot Web Convert HTML String to PDF File

Add dependencies to the Spring Boot Web project

At this first step we add the Flying Saucer PDF Rendering (OpenPDF) and Apache Commons IO dependencies to the Spring Boot project.

If you use Gradle build project, add the following dependencies to the build.gradle file.

implementation group: 'org.xhtmlrenderer', name: 'flying-saucer-pdf-openpdf', version: '9.1.22'
implementation group: 'commons-io', name: 'commons-io', version: '2.11.0'

If you use Maven build project, add the following dependencies to the pom.xml file.

<dependency>
    <groupId>org.xhtmlrenderer</groupId>
    <artifactId>flying-saucer-pdf-openpdf</artifactId>
    <version>9.1.22</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

Implement PDF Service to Convert HTML to PDF

At this step we implement a PDF service class to convert a given HTML String into PDF file as a byte array.

Add a new Java package named dev.simplesolution.springboothtmlpdf.service and create new interface named PdfService as following Java code.

src/main/java/dev/simplesolution/springboothtmlpdf/service/PdfService.java

package dev.simplesolution.springboothtmlpdf.service;

import java.io.ByteArrayInputStream;

public interface PdfService {
    ByteArrayInputStream convertHtmlToPdf(String htmlContent);
}

Add a new Java package named dev.simplesolution.springboothtmlpdf.service.impl and create a new Java class named PdfServiceImpl with Java code as below.

src/main/java/dev/simplesolution/springboothtmlpdf/service/impl/PdfServiceImpl.java

package dev.simplesolution.springboothtmlpdf.service.impl;

import dev.simplesolution.springboothtmlpdf.service.PdfService;
import org.springframework.stereotype.Service;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

@Service
public class PdfServiceImpl implements PdfService {

    @Override
    public ByteArrayInputStream convertHtmlToPdf(String htmlContent) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocumentFromString(htmlContent);
        renderer.layout();
        renderer.createPDF(outputStream, false);
        renderer.finishPDF();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        return inputStream;
    }
}

Implement Controller class and HTML view

At this step we implement the HTML view to allow user input the HTML String to generate PDF files. And the controller class to handle downloading generated PDF file.

Add a new Java package named dev.simplesolution.springboothtmlpdf.controller and implement the controller class named PdfController as below Java code.

src/main/java/dev/simplesolution/springboothtmlpdf/controller/PdfController.java

package dev.simplesolution.springboothtmlpdf.controller;

import dev.simplesolution.springboothtmlpdf.service.PdfService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;

@Controller
public class PdfController {

    @Autowired
    private PdfService pdfService;

    @GetMapping("/")
    public String index() {
        return "index";
    }

    @PostMapping("/generatePdfFile")
    public void generatePdfFile(HttpServletResponse response, String contentToGenerate) throws IOException {
        ByteArrayInputStream byteArrayInputStream = pdfService.convertHtmlToPdf(contentToGenerate);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=file.pdf");
        IOUtils.copy(byteArrayInputStream, response.getOutputStream());
    }

}

And add a new html file named index.html under resources/templates folder as below HTML code.

src/main/resources/templates/index.html

<html xmlns:th="https://www.thymeleaf.org">
<head>
    <title>Spring Boot Web Generate PDF File from HTML String</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <h1>Generate PDF File from HTML String</h1>
    <form method="POST" enctype="multipart/form-data" action="/generatePdfFile">
        <div class="mb-3">
            <label for="contentToGenerate" class="form-label">Enter your HTML content to generate PDF file</label>
            <textarea class="form-control form-control-lg" id="contentToGenerate" name="contentToGenerate" required></textarea>
        </div>
        <div class="mb-3">
            <button type="submit" class="btn btn-primary">Generate PDF File</button>
        </div>
    </form>
</div>
</body>
</html>

Complete Source Code and Run the Web Application

At this step we have finished the Spring Boot web application which allow convert HTML String to PDF file, the final source code structure as below screenshot.

Spring Boot Web Convert HTML String to PDF File

Run the Spring Boot web application and open http://localhost:8080/ on your browser to access the web page as below screenshot.

Spring Boot Web Convert HTML String to PDF File

Input the HTML code below to text area field.

<!DOCTYPE HTML>
<html>
    <body>
        <h1>Hello Simple Solution</h1>
        <img width="140" src="https://simplesolution.dev/images/Logo_S_v1.png" />
     </body>
</html>

Click Generate PDF File button to generate and download the PDF file.

Spring Boot Web Convert HTML String to PDF File

Open the downloaded file.pdf file we have the PDF file content from HTML as following screenshot.

Spring Boot Web Convert HTML String to PDF File

You can try another test with more complex HTML content as below.

<!DOCTYPE HTML>
<html>
<head>
    <style>
        h1 {
            color: #25a7e7;
            text-align: center;
        }
        .receipt-header {
            width: 100%;
        }
        .receipt {
            width: 100%;
        }
        .receipt, .receipt th, .receipt td {
            border: 1px solid #25a7e7;
            border-collapse: collapse;
        }
        .receipt th {
            background-color: #25a7e7;
            color: white;
        }
        .total {
            text-align: right;
        }
    </style>
</head>
<body>
<h1>Receipt</h1>
<div>
    <table class="receipt-header">
        <tr>
            <td>
                <table>
                    <tr>
                        <th>Bill To:</th>
                    </tr>
                    <tr>
                        <td>Company Name: Simple Solution</td>
                    </tr>
                    <tr>
                        <td>Address: 123 Sample Street</td>
                    </tr>
                    <tr>
                        <td>Email: info@simplesolution.dev</td>
                    </tr>
                    <tr>
                        <td>Phone: 123 456 789</td>
                    </tr>
                </table>
            </td>
            <td align="right">
                <img width="140" src="https://simplesolution.dev/images/Logo_S_v1.png" />
                <br />
                Simple Solution
            </td>
        </tr>
    </table>
</div>

<br />
<table class="receipt">
    <tr>
        <th>Item #</th>
        <th>Description</th>
        <th>Quantity</th>
        <th>Unit Price</th>
        <th>Total</th>
    </tr>
    <tr>
        <td>1</td>
        <td>Item 1 Description</td>
        <td>5</td>
        <td>$100</td>
        <td>$500</td>
    </tr>
    <tr>
        <td>2</td>
        <td>Item 2 Description</td>
        <td>10</td>
        <td>$20</td>
        <td>$200</td>
    </tr>
    <tr>
        <td>3</td>
        <td>Item 3 Description</td>
        <td>2</td>
        <td>$50</td>
        <td>$100</td>
    </tr>
    <tr>
        <td class="total" colspan="4"><b>Total</b></td>
        <td><b>$800</b></td>
    </tr>
</table>
</body>
</html>

Download The Source Code

The source code in this tutorial can be found at: github.com/simplesolutiondev/spring-boot-web-html-to-pdf

or clone at:

git clone https://github.com/simplesolutiondev/spring-boot-web-html-to-pdf.git

or download at:

Download Source Code

Happy Coding 😊

Spring Boot Generate PDF File from HTML Template

Spring Boot Web Download PDF File from HTML Template

Java Export PDF File from HTML Template

Java Convert HTML to PDF

Java Convert HTML to Image