Skip to main content
AI
  • Get started with AI

    • Red Hat AI

      Accelerate the development and deployment of enterprise AI solutions.

    • AI learning hub

      Explore learning materials and tools, organized by task.

    • AI interactive demos

      Click through scenarios with Red Hat AI, including training LLMs and more.

    • AI/ML learning paths

      Expand your Red Hat OpenShift AI knowledge using these learning resources.

    • AI quickstarts

      Focused AI use cases designed for fast deployment on Red Hat AI platforms.

    • No-cost AI training

      Foundational Red Hat AI training.

  • Featured resources

    • Red Hat OpenShift AI
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

Red Hat AI Factory with NVIDIA

Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.

Learn
  • Self-guided

    • Documentation

      Find answers, get step-by-step guidance, and learn how to use Red Hat products.

    • Learning paths

      Explore curated walkthroughs for common development tasks.

    • Guided learning

      Receive custom learning paths powered by our AI assistant.

    • See all learning
  • Hands-on

    • Developer Sandbox

      Spin up Red Hat's products and technologies without setup or configuration.

    • Interactive labs

      Learn by doing in these hands-on, browser-based experiences.

    • Interactive demos

      Click through product features in these guided tours.

  • Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics
  • Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
Build
  • Get started

    • Red Hat build of Podman Desktop

      A downloadable, local development hub to experiment with our products and builds.

    • Developer Sandbox

      Spin up Red Hat's products and technologies without setup or configuration.

  • Download products

    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products
  • Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset
  • References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
Community
  • Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions
  • Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github
  • Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

Join the Red Hat Developer program

Download Red Hat products and project builds, access support documentation, learning content, and more.

ConsoleDocsSupport Search
New For you

Recommended

We'll recommend resources you may like as you browse. Try these suggestions for now.

  • Product downloads
  • Cheat sheets
  • Red Hat Developer learning portal
  • Developer blog
  • E-books
  • Developer Sandbox
Log in

Get more with a Red Hat Developer account

  • Product downloads
  • Console access
  • Event registration
  • Training & trials
Explore more account benefitsLog in or register

A subscription may be required for some services.

Contact us

An easier way to generate PDFs from HTML templates

March 11, 2022
Muhammad Edwin
Related topics:
JavaLinuxOpen sourceSpring Boot
Related products:
Red Hat Enterprise Linux

    Applications frequently are required to generate invoices, reports, ID cards, and much more in PDF format. There are Java libraries and tools that developers can use to generate PDFs, including the popular JasperReports. While sophisticated, using these programs can be complicated because they support a wide range of documents.

    This article introduces a simpler tool, the open source wkhtmltopdf utility. I will show you how to use wkhtmltopdf to solve a common scenario: You have an HTML form, parameterized to accept input data, and you need to produce a PDF from the data in that form. You will learn how to set up your data and make a call to the wkhtmltopdf utility from a Spring Boot web application. We'll use Red Hat's Universal Base Image (UBI) 8 as a base image to simplify the application build, then deploy the final image into Red Hat Openshift 4.

    Note: You can find the code for the example in my GitHub repository.

    Configuration using Maven

    Let's start with a Maven file. I'm using a Snowdrop bill of materials (BOM) on my Maven project object model (POM) file instead of a community version of Spring Boot:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.edw</groupId>
        <artifactId>SpringBootAndPdf</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <repositories>
            <repository>
                <id>redhat-early-access</id>
                <name>Red Hat Early Access Repository</name>
                <url>https://maven.repository.redhat.com/earlyaccess/all/</url>
            </repository>
            <repository>
                <id>redhat-ga</id>
                <name>Red Hat GA Repository</name>
                <url>https://maven.repository.redhat.com/ga/</url>
            </repository>
        </repositories>
    
    
        <pluginRepositories>
            <pluginRepository>
                <id>redhat-early-access</id>
                <name>Red Hat Early Access Repository</name>
                <url>https://maven.repository.redhat.com/earlyaccess/all/</url>
            </pluginRepository>
            <pluginRepository>
                <id>redhat-ga</id>
                <name>Red Hat GA Repository</name>
                <url>https://maven.repository.redhat.com/ga/</url>
            </pluginRepository>
        </pluginRepositories>
    
        <properties>
            <snowdrop-bom.version>2.4.9.Final-redhat-00001</snowdrop-bom.version>
            <spring-boot.version>2.1.4.RELEASE-redhat-00001</spring-boot.version>
            <maven.compiler.source>11</maven.compiler.source>
            <maven.compiler.target>11</maven.compiler.target>
        </properties>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>dev.snowdrop</groupId>
                    <artifactId>snowdrop-dependencies</artifactId>
                    <version>${snowdrop-bom.version}</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
        </dependencies>
    
    
        <build>
            <finalName>app</finalName>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                    <version>${spring-boot.version}</version>
                    <configuration>
                        <mainClass>com.edw.Main</mainClass>
                    </configuration>
                    <executions>
                        <execution>
                            <goals>
                                <goal>repackage</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
            </plugins>
        </build>
    
    </project>

    The Spring Boot program

    Our main class in Java is:

    package com.edw;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class Main {
        public static void main(String[] args) {
            SpringApplication.run(Main.class, args);
        }
    }

    The following Controller class displays a generated PDF. One of the class's most important tasks is to display the PDF properly in a browser; this task is achieved by setting up a proper MediaType that produces an application/pdf content-type header. Another important task is to call an external process that runs wkhtmltopdf to trigger the conversion from HTML to PDF:

    package com.edw.controllers;
    
    import org.springframework.http.MediaType;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.Scanner;
    import java.util.UUID;
    
    @Controller
    public class ReportController {
    
        @GetMapping(
                value = "/generate-report",
                produces = MediaType.APPLICATION_PDF_VALUE
        )
        public @ResponseBody byte[] generateReport(@RequestParam(value = "name") String name,
                                                   @RequestParam(value = "address") String address) throws Exception {
            String uuid = UUID.randomUUID().toString();
            Path pathHtml = Paths.get("/tmp/" + uuid + ".html");
            Path pathPdf = Paths.get("/tmp/" + uuid + ".pdf");
    
            try {
                // read the template and fill the data
                String htmlContent = new Scanner(getClass().getClassLoader().getResourceAsStream("template.html"), "UTF-8")
                                        .useDelimiter("\\A")
                                        .next();
                htmlContent = htmlContent.replace("$name", name)
                                            .replace("$address", address);
    
                // write to html
                Files.write(pathHtml, htmlContent.getBytes());
    
                // convert html to pdf
                Process generateToPdf = Runtime.getRuntime().exec("wkhtmltopdf " + pathHtml.toString() + " " + pathPdf.toString() );
                generateToPdf.waitFor();
    
                // deliver pdf
                return Files.readAllBytes(pathPdf);
    
            } finally {
                // delete temp files
                Files.delete(pathHtml);
                Files.delete(pathPdf);
            }
        }
    }

    Formatting the HTML data

    The following HTML template generates a report with input data consisting of names (the $name parameter) and addresses (the $address parameter):

    <html>
    <head>
        <style>
    		<!-- put your css here -->
        </style>
    </head>
    <body>
        <div class="container" style="padding-top: 100px;">
            <div class="row justify-content-center">
                <div class="col-md-6">
                    <table class="table table-bordered">
                        <thead class="thead-light">
                            <tr>
                                <th>Name</th>
                                <th>Address</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>$name</td>
                                <td>$address</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </body>
    </html>

    Installing the wkhtmltopdf program

    This next part is where the magic happens. First, you need to download wkhtmltopdf from GitHub and extract the program. After that, you can create a wkhtml folder within your Java project and copy wkhtmltopdf to the application's folder from the bin folder:

    $ wget https://github.com/wkhtmltopdf/wkhtmltopdf/releases/download/0.12.4/wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
    
    $ tar -xf wkhtmltox-0.12.4_linux-generic-amd64.tar.xz
    
    $ mkdir /code/wkhtml
    
    $ cp wkhtmltox/bin/wkhtmltopdf /code/wkhtml/

    The resulting directory structure looks like:

    +--- .gitignore
    +--- Dockerfile
    +--- pom.xml
    +--- src
    |   +--- main
    |   |   +--- java
    |   |   |   +--- com
    |   |   |   |   +--- edw
    |   |   |   |   |   +--- controllers
    |   |   |   |   |   |   +--- HelloWorldController.java
    |   |   |   |   |   |   +--- ReportController.java
    |   |   |   |   |   +--- Main.java
    |   |   +--- resources
    |   |   |   +--- application.properties
    |   |   |   +--- template.html
    |   +--- test
    |   |   +--- java
    +--- wkhtml
    |   +--- wkhtmltopdf

    Building the image

    The following Dockerfile uses UBI 8 as the base image:

    FROM registry.access.redhat.com/ubi8/openjdk-11-runtime:1.10
    
    USER root
    
    ENV LANG='en_US.UTF-8' LANGUAGE='en_US:en' TZ='Asia/Jakarta'
    
    RUN microdnf update && \
        microdnf install tzdata libXrender libXext fontconfig  && \
        ln -sf /usr/share/zoneinfo/$TZ /etc/localtime && \
        microdnf clean all
    
    COPY wkhtml/wkhtmltopdf /usr/local/bin/
    
    EXPOSE 8080
    USER 185
    
    COPY target/app.jar /deployments/app.jar
    ENTRYPOINT [ "java", "-jar", "/deployments/app.jar" ]

    Now, build your image and run it:

    $ docker build -t springboot-and-pdf . 
    
    $ docker run -p 8080:8080  springboot-and-pdf

    In your browser, enter the generate-report URL with a name and address as parameters, and you get a PDF ready to download and print, as shown in Figure 1.

    The application displays a PDF reflecting the application's HTML template.
    Figure 1. The Spring Boot application generates a PDF report from the data in an HTML template.

    Conclusion

    The streamlined process shown in this example is useful in a variety of situations where you want to generate a report with tabular data or another structured PDF based on input data. Feel free to leave comments on this article to discuss where you might use this approach and any questions you may have.

    Last updated: July 31, 2023

    Related Posts

    • Node.js - Harnessing the power of Java (for PDF generation and more)

    • Eclipse MicroProfile for Spring Boot developers

    • Migrating Spring Boot tests to Quarkus

    Recent Posts

    • A day in the life of an NVIDIA H100 on Red Hat OpenShift 5

    • Migrate BuildConfigs to builds for Red Hat OpenShift with one plug-in install

    • Run Red Hat Enterprise Linux CoreOS on NVIDIA BlueField DPUs

    • Agent harness engineering: Separating model capabilities from enforcement

    • What's new for developers in Red Hat Enterprise Linux 10.3 and 9.9

    Red Hat Developers logo

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    Red Hat Developer

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility
    Ask AI