Generating PDFs from HTML in Micronaut: A Comprehensive Guide

Generating PDF documents from HTML content is a common requirement in web applications. Micronaut, with its flexible and extensible architecture, makes it easy to achieve this. In this blog post, we will walk you through the process of creating PDFs from HTML content in a Micronaut application.

Step 1: Add Dependencies

The first step is to add the necessary dependencies to your build.gradle (for Groovy) or build.gradle.kts (for Kotlin) file. Open your project’s build file and add the following dependencies:

implementation 'org.jsoup:jsoup:1.15.1'
implementation 'com.openhtmltopdf:openhtmltopdf-pdfbox:1.0.10'

Step 2: Convert your HTML String to Document

If you want to know how to create a dynamic HTML, do check out Integrating Thymeleaf in Micronaut: A Step-by-Step Guide

We will pass HTML string to Jsoup library to convert into Document

private fun getHtmlDocument(html: String): Document {
        val document: Document = Jsoup.parse(html, "UTF-8")
        
document.outputSettings().syntax(Document.OutputSettings.Syntax.xml)
        return document
    }

Step 3: Use PdfRendererBuilder to build Pdf from HTML

In this controller, we define a generatePdf method that generates a PDF from the HTML content. We use PdfRendererBuilder to convert the html to pdf and save it to a file.

@Get("/generate-pdf")
    suspend fun generatePdf() {
        var html = testThymeleaf()
        val outputPath = "/Users/bhanu/temp/your_filename.pdf"
        val document = getHtmlDocument(html)
        FileOutputStream(outputPath).use { os ->
            val builder = PdfRendererBuilder()
            builder.withUri(outputPath)
            builder.toStream(os)
            builder.withW3cDocument(W3CDom().fromJsoup(document), "/")
            builder.run()
        }
    }

Implementation: https://github.com/cw-bhanunadar/Micronaut-playground/pull/8/files

Output: your_filename.pdf

Related Post