# How to Convert HTML to PDF using OpenPDF

> Learn the step-by-step process to efficiently convert HTML to PDF in Java applications using the OpenPDF library

- **Author**: Pedro Campos
- **Published**: 2024-02-01
- **Updated**: 2026-03-09
- **Category**: Tutorials
- **Tags**: how-to, java, openpdf
- **Read time**: 7 min read
- **URL**: https://templated.io/blog/how-to-convert-html-to-pdf-using-openpdf/

---

## Introduction

If you're looking for turning HTML to PDF using OpenPDF, you're probably working on invoices, reports, or other documents where a consistent layout really matters.

OpenPDF is a free Java library for making PDFs. It gives you flexibility in Java projects, but you need to set it up correctly and know how it handles HTML.

I'm Pedro, and I founded Templated, an API for generating images, PDFs, and videos.

In this guide, I'll show you step by step how to convert HTML to PDF with OpenPDF. But keep in mind, it doesn't scale well.

I'll also share the solution I built to handle dynamic PDF generation at scale, while keeping formatting and rendering reliable.

Let's get started.

## Why Choose OpenPDF?

- Open Source: OpenPDF is entirely open-source, allowing for customization and community-driven enhancements.
- Simplicity: It offers a straightforward API, making it accessible for beginners and efficient for experienced developers.
- Compatibility: OpenPDF is compatible with a wide range of Java applications, ensuring seamless integration.
- Feature-Rich: Despite its simplicity, OpenPDF supports a variety of PDF features commonly found in [Document Management Software](https://www.techimply.com/software/document-management-software), including document manipulation, text formatting, and image inclusion.

If you're exploring different approaches within the Java ecosystem, you can also check out our complete guide on how to [convert HTML to PDF with Java](https://templated.io/blog/how-to-convert-html-to-pdf-with-java/) to understand alternative methods and libraries available.

## Getting Started with OpenPDF

### Step 1: Add OpenPDF Dependency

To begin, you need to include OpenPDF in your Java project. For Maven users, add the following dependency to your `pom.xml` file:

xmlCopy code

```xml
<dependency>
    <groupId>com.github.librepdf</groupId>
    <artifactId>openpdf</artifactId>
    <version>1.3.26</version>
</dependency>
```

This dependency will include OpenPDF in your project, enabling you to use its functionality to create and manipulate PDF documents.

### Step 2: Convert HTML to PDF

Once OpenPDF is added to your project, you can start converting HTML content to PDF. The following Java code example illustrates this process:

```java
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.io.StringReader;

public class HtmlToPdfOpenPDF {
    public static void main(String[] args) {
        Document document = new Document();
        try {
            PdfWriter.getInstance(document, new FileOutputStream("ConvertedHtmlToPdf.pdf"));
            document.open();
            String htmlContent = "<html><head><title>Sample HTML</title></head><body><h1>Hello, OpenPDF!</h1><p>This is a paragraph in the generated PDF.</p></body></html>";
            HTMLWorker htmlWorker = new HTMLWorker(document);
            htmlWorker.parse(new StringReader(htmlContent));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
        System.out.println("PDF created successfully.");
    }
}
```

In this example:

- A `Document` object is created, representing the PDF document.
- The `PdfWriter` instance links the document to a file output stream, specifying the PDF file's name.
- The `HTMLWorker` class parses the HTML content and adds it to the `Document`.
- Finally, the document is closed, and the PDF is saved with the HTML content rendered inside.

## Advanced Features

While the above example covers basic HTML to PDF conversion, OpenPDF also supports more advanced features, such as:

- Styling with CSS: You can include CSS styles within your HTML content to control the appearance of the PDF content.
- Image Inclusion: HTML tags for images (`<img>`) are supported, allowing you to embed images in your PDF.
- Font Customization: OpenPDF allows for font customization, enabling you to maintain brand consistency or enhance the document's aesthetics.

### Adding CSS and Images

To include CSS and images in your HTML content, ensure that your HTML string includes the necessary CSS styles and image tags. OpenPDF will process these elements during the conversion.

### Custom Fonts

To use custom fonts, you can use OpenPDF's font classes to define and set fonts in your document. This requires additional steps to load and set the font for document elements.

## Creating PDF from a URL

In some cases, you might want to create a PDF from the content available at a specific URL. Here's how you can achieve this using OpenPDF:

```java
import com.lowagie.text.Document;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.pdf.PdfWriter;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class UrlToPdfOpenPDF {
    public static void main(String[] args) {
        // Specify the URL of the HTML page
        String webpageUrl = "http://example.com";

        // Initialize a StringBuilder to hold the HTML content
        StringBuilder htmlStringBuilder = new StringBuilder();

        try {
            // Create a URL object from the webpage URL
            URL url = new URL(webpageUrl);

            // Open a connection to the URL
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // Set the request method to GET
            connection.setRequestMethod("GET");

            // Read the response from the URL
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            while ((inputLine = bufferedReader.readLine()) != null) {
                htmlStringBuilder.append(inputLine);
            }
            bufferedReader.close();

            // Convert the StringBuilder to a String containing the HTML content
            String htmlContent = htmlStringBuilder.toString();

            // Use OpenPDF to convert the HTML content to a PDF
            Document document = new Document();
            PdfWriter.getInstance(document, new FileOutputStream("UrlToPdf.pdf"));
            document.open();
            HTMLWorker htmlWorker = new HTMLWorker(document);
            htmlWorker.parse(new InputStreamReader(new java.io.ByteArrayInputStream(htmlContent.getBytes())));
            document.close();

            System.out.println("PDF created successfully from URL.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

This section demonstrates how to programmatically fetch HTML content from a specified URL and convert it into a PDF document using OpenPDF.

If you only have a few HTML files to convert and don't need a full Java setup, you can also use our [free HTML to PDF converter](https://templated.io/tools/html-to-pdf/) tool for quick conversions without breaking the formatting.

## A Faster Approach to PDF Automation with Templated

If you need to generate dynamic PDFs where data changes but layout must remain precise for [use cases](https://templated.io/use-cases/) like invoices, certificates, reports, contracts, and more, traditional Java libraries like OpenPDF, [Flying Saucer](https://templated.io/blog/how-to-convert-html-to-pdf-using-flying-sauce/), and iText start to feel heavy.

**They require -**

Manual layout handling. Manage rendering logic. Deal with formatting edge cases.

And scaling bulk generation means more infrastructure, more memory management, more maintenance. They are workarounds, not automation systems.

When efficiency, speed, and design consistency matter, the better approach is to use a solution built specifically for PDF automation.

I built [Templated](https://templated.io) (a [PDF generation API](https://templated.io/pdf-generator-api/)) to solve this exact problem. It is not just converting content to PDF, but generating dynamic, design-consistent documents at scale. It's built to handle automation workflows cleanly, without forcing you to manage rendering engines or document infrastructure.

This isn't just an API endpoint.

It's a complete template-driven generation system.

**Here's what makes it different:**

### Create Templates Your Way

Templated gives you multiple ways to build PDF templates:

- Visual drag-and-drop editor (Canva-like experience)
- 100+ [pre-built templates](https://templated.io/templates/)
- Directly import PDFs and designs from [Canva](https://templated.io/canva-import/)
- [Build your PDF templates with AI](https://templated.io/ai-template-generator/)

You can define dynamic layers like name, date, invoice number, or custom fields, and update them programmatically.

Check out how the Templated design editor works in action:

[Watch the video on YouTube](https://www.youtube.com/watch?v=WXH5XcbSLuA)

### Built for Automation

Templated supports automation across different workflows:

- Spreadsheet-based bulk generation
- Integration with no-code tools like Make, Zapier, and n8n
- Java and other programming language integrations
- MCP support

Whether you're a developer integrating via API or a team running bulk generation from spreadsheets, the workflow stays simple.

### Production-Ready Performance

- Fast rendering (seconds per document)
- Scalable for high-volume generation
- Reliable infrastructure
- Zero maintenance on your side

This flexibility allows you to generate hundreds or even thousands of PDFs in minutes while maintaining a consistent design.

### Ready to Try It?

[Sign up](https://app.templated.io/signup) for free and get **50 credits** to test the Templated API.

Inside your dashboard, you'll find your unique API key.

![Shows where to get the API key from the Dashboard](https://templated-assets.s3.us-east-1.amazonaws.com/site/blog/api-key-example.png)

From there, create a new template or import one, then define the dynamic layers you want to update.

Once that's set up, you can send your data from your backend, a spreadsheet, or a no-code workflow. Templated will generate hundreds or even thousands of PDFs automatically.

You decide how to use the output: return a secure link, download the file, store it in your system, or automate delivery to cloud storage.

If you want to know more about how to use it in different workflows, explore our blog:

- [Automate your image generation using spreadsheets](https://templated.io/blog/automate-image-generation-with-spreadsheets/)
- [Quickly build a base template with AI for your automation](https://templated.io/blog/ai-template-generator/)
- [Automate Certificate Generation With Google Sheets, Make, and Templated](https://templated.io/blog/automate-certificate-generation/)

### Other Languages

Here are several programming languages besides Java that can convert HTML to PDF.

- [Convert HTML to PDF with C#](https://templated.io/blog/how-to-convert-html-to-pdf-with-c-sharp/)
- [Convert HTML to PDF with PHP](https://templated.io/blog/how-to-convert-html-to-pdf-with-php/)
- [Convert HTML to PDF with Node.js](https://templated.io/blog/how-to-convert-html-to-pdf-with-nodejs/)
- [Convert HTML to PDF with Python](https://templated.io/blog/how-to-convert-html-to-pdf-with-python/)

### Limitations of OpenPDF

OpenPDF is a reliable Java library for PDF generation, but it has limitations when working with HTML-based workflows.

- Limited native support for modern HTML/CSS rendering
- Manual layout and formatting handling
- Scaling bulk generation requires infrastructure management
- No built-in automation layer

It works well for controlled use cases, but high-volume or dynamic document automation requires additional setup.

### Conclusion

OpenPDF is a reliable Java library for converting HTML to PDF in controlled environments. It works well when you're comfortable managing layout, rendering, and infrastructure yourself.

But once you need dynamic templates, bulk generation, or scalable document workflows, the complexity increases. At that point, you're not just converting files, you're maintaining a system.

For true PDF automation at scale, a template-driven API approach makes more sense.

[Sign up](https://app.templated.io/signup) for [Templated](https://templated.io) and start generating dynamic, production-ready PDFs in minutes.
