· tutorials · 11 min read

How To Convert HTML to PDF with Python (Best for 2024)

Learn different approaches on how to convert HTML to PDF and pick the one best for your needs

Learn different approaches on how to convert HTML to PDF and pick the one best for your needs

Introduction

Creating PDFs programmatically in Python is a common task, and although there’s no single correct method for doing so, certain approaches can be more efficient and faster than others.
This article explores some of the most efficient methods for converting HTML to PDF using Python.

Why create PDF from HTML?

Here are some reasons on why generating PDFs from HTML is a good idea:

  • Market Norm: HTML serves as the internet’s foundation, providing a universally accepted and widespread method for organizing content.
  • Established Technology: Open standards ensure HTML compatibility across an extensive array of tools and technologies.
  • Flexibility: The availability of numerous tools eases the process of conversion.
  • CSS Customization: Employ CSS for intricate styling within PDF documents.
  • Media Integration: HTML offers a solid foundation for creating documents enriched with multimedia elements.

To sum up, changing HTML into PDFs brings together the best aspects of both: HTML’s flexibility, accessibility, and interactivity, and the portability and standardization of PDFs.

HTML to PDF using Python Libraries

Many Python libraries exist for creating PDFs from HTML content, and some of these are detailed below.

1. Pyppeteer

Pyppeteer is a Python port of Puppeteer, providing a high-level API to control Chrome/Chromium over the DevTools Protocol. It can be used for web scraping, taking screenshots, and generating PDFs from HTML. For a detailed guide on using Pyppeteer for PDF and image generation, see this article.

Let’s explore how we can use pyppeteer to create PDFs from HTML.

Step 1: Install Pyppeteer

First, we need to install pyppeteer with the following command:

Terminal window
pip install pyppeteer

Step 2: Python code to convert HTML to PDF with Pyppeteer

import asyncio
from pyppeteer import launch
async def create_pdf(url, pdf_path):
browser = await launch()
page = await browser.newPage()
await page.goto(url)
await page.pdf({'path': pdf_path, 'format': 'A4'})
await browser.close()
# Run create_pdf
asyncio.get_event_loop().run_until_complete(generate_pdf('https://google.com', 'google_example.pdf'))

In the generate_pdf method of the code, the following steps are taken:

  1. A new browser instance is launched in headless mode.
  2. A new page is opened in the browser, and it waits until the page is ready.
  3. The browser navigates to the URL provided in the url argument and waits for the page to fully load.
  4. A PDF of the webpage is generated and saved to the location specified in pdf_path, with the format (dimensions) set to A4.
  5. The headless browser is then closed.

Now, to generate a PDF from custom HTML this is the code and process:

import asyncio
from pyppeteer import launch
async def create_pdf_from_html(html, pdf_path):
browser = await launch()
page = await browser.newPage()
await page.setContent(html)
await page.pdf({'path': pdf_path, 'format': 'A4'})
await browser.close()
# HTML content
html = '''
<html>
<head>
<title>PDF Example</title>
</head>
<body>
<h1>Hey, this will turn into a PDF!</h1>
</body>
</html>
'''
# Run create_pdf_from_html
asyncio.get_event_loop().run_until_complete(generate_pdf_from_html(html, 'from_html.pdf'))

The method generate_pdf_from_html in the Pyppeteer example above demonstrates how to generate PDFs using custom HTML content. Here’s what happens in this approach:

  1. A new headless browser instance is launched.
  2. A new page is opened in the headless browser, and it waits until it is ready.
  3. The content of the page is explicitly set to our custom HTML content.
  4. A PDF of the webpage is generated and saved to the location specified in pdf_path, with the format set to ‘A4’.
  5. The headless browser is closed.

2. python-pdfkit

python-pdfkit is a Python wrapper for the wkhtmltopdf utility, which uses Webkit to convert HTML to PDF. For a detailed guide on using python-pdfkit, see this article.

Step 1: Install python-pdfkit

First, let’s install python-pdfkit with pip:

Terminal window
pip install pdfkit

Step 2: Python code to convert website URL to PDF with python-pdfkit

import pdfkit
# URL to fetch
url = 'https://engadget.com'
# PDF path to save
pdf_path = 'example.pdf'
pdfkit.from_url(url, pdf_path)

pdfkit supports generating PDFs from website URLs out of the box just like Pyppeteer.

In the above code, as you can see, pdfkit is generating pdf just from one line code. pdfkit.from_url is all you need to generate a PDF.

Step 3: Generating PDF from custom HTML content

import pdfkit
# HTML content
html = '''
<html>
<head>
<title>PDF Example</title>
</head>
<body>
<h1>Hey, this will turn into a PDF!</h1>
</body>
</html>
'''
# PDF path to save
pdf_path = 'example.pdf'
# Create PDF
pdfkit.from_string(html, pdf_path)

To generate a PDF from custom HTML content using python-pdfkit, you simply need to use pdfkit.from_string and provide the HTML content along with the path for the PDF file.

3. xhtml2pdf

xhtml2pdf is a Python library that enables the creation of PDFs from HTML content with a slightly different approach. Let’s take a look at xhtml2pdf in use. For a detailed guide on using xhtml2pdf, see this article.

Step 1: Install xhtml2pdf

To install xhtml2pdf, use the following command:

Terminal window
pip install xhtml2pdf requests

Step 2: Generate PDF from a website URL with xhtml2pdf:

It’s important to note that xhtml2pdf doesn’t have a built-in feature to parse URLs. However, we can use the requests library in Python to retrieve content from a URL.

from xhtml2pdf import pisa
import requests
def url_to_pdf(url, pdf_path):
# Retrieve the HTML content from the URL
response = requests.get(url)
if response.status_code != 200:
print(f"Failed to retrieve from URL: {url}")
return False
html_content = response.text
# Create PDF
with open(pdf_path, "wb") as pdf_file:
pisa_status = pisa.CreatePDF(html_content, dest=pdf_file)
return not pisa_status.err
# URL to retrieve
url_to_retrieve = "https://bbc.com"
# PDF path to save
pdf_path = "bbc.pdf"
# Create PDF
url_to_pdf(url_to_retrieve, pdf_path)

In the url_to_pdf method of the code, the following steps are performed:

  1. We use the requests library to fetch the webpage content from the specified URL.
  2. After receiving the content, we extract the text portion using response.text.
  3. Next, for creating the PDF, we use pisa.CreatePDF. Here, we pass our HTML content and the name for the output PDF file.

Step 3: Create a PDF from custom HTML content using xhtml2pdf:

from xhtml2pdf import pisa
def convert_html_to_pdf(html_string, pdf_path):
with open(pdf_path, "wb") as pdf_file:
pisa_status = pisa.CreatePDF(html_string, dest=pdf_file)
return not pisa_status.err
# HTML content
html = '''
<html>
<head>
<title>PDF Example</title>
</head>
<body>
<h1>Hey, this will turn into a PDF!</h1>
</body>
</html>
'''
# Create PDF
pdf_path = "example.pdf"
convert_html_to_pdf(html, pdf_path):

Creating a PDF from custom HTML content is similar to the process for URLs, with just one key difference: instead of passing a URL, we directly provide the actual HTML content to our creation method. The method then uses this custom HTML content to create the PDF.

4. Playwright

Playwright is a modern, lightweight library for headless browser automation. It supports multiple browsers (Firefox, Chromium, Edge, Safari) across platforms and languages, making it versatile for tasks like PDF generation.

To use Python as a converter for HTML to PDF with Playwright, follow these steps:

Step 1: Install Playwright:

Terminal window
pip install playwright
playwright install

Step 2: Generate PDF from Website URL:

import asyncio
from playwright.async_api import async_playwright
async def url_to_pdf(url, output_path):
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
await page.goto(url)
await page.pdf(path=output_path)
await browser.close()
# Example usage
url = 'https://example.com'
output_path = 'example_url.pdf'
asyncio.run(url_to_pdf(url, output_path))

Step 3: Generate PDF from Custom HTML Content:

import asyncio
from playwright.async_api import async_playwright
async def html_to_pdf(html_content, output_path):
async with async_playwright() as p:
browser = await p.chromium.launch()
page = await browser.new_page()
await page.set_content(html_content)
await page.pdf(path=output_path)
await browser.close()
html_content = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sample HTML</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a sample HTML content to be converted to PDF.</p>
</body>
</html>
'''
output_path = 'custom_html.pdf'
asyncio.run(html_to_pdf(html_content, output_path))

5. WeasyPrint

WeasyPrint is a visual rendering engine that follows the W3C specifications for HTML and CSS. It’s known for its excellent CSS support and ability to generate high-quality PDFs without requiring external dependencies like browsers or rendering engines.

Step 1: Install WeasyPrint:

Terminal window
pip install weasyprint

Step 2: Generate PDF from Website URL:

from weasyprint import HTML
def url_to_pdf(url, output_path):
HTML(url=url).write_pdf(output_path)
# Example usage
url = 'https://example.com'
output_path = 'example_url.pdf'
url_to_pdf(url, output_path)

Step 3: Generate PDF from Custom HTML Content:

from weasyprint import HTML
def html_to_pdf(html_content, output_path):
HTML(string=html_content).write_pdf(output_path)
html_content = '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample HTML</title>
<style>
body { font-family: Arial, sans-serif; }
h1 { color: navy; }
</style>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a sample HTML content to be converted to PDF.</p>
</body>
</html>
'''
output_path = 'custom_html.pdf'
html_to_pdf(html_content, output_path)

Comparing Pyppeteer, python-pdfkit, xhtml2pdf, Playwright, and WeasyPrint

While each of these tools primarily focuses on converting HTML to PDF, they each offer unique features and methods.

Below, you’ll find a detailed table comparing these tools to help you select the one that best fits your requirements.

LibraryProsConsBest ForPerformanceMemory UsageCSS SupportJavaScript SupportUnicode SupportPriceActive Development
PyppeteerProvides a full browser environment with comprehensive JS and CSS support. Easy to use API.Performance may vary. Requires Chrome/Chromium installation. Higher resource usage.Handling intricate web content, single-page applications (SPAs), and dynamic JS content.MediumHighExcellentExcellentYesFreeActive
xhtml2pdfPure Python easy setup. Good for simpler HTML/CSS documents. Low resource usage.Limited JavaScript and CSS support. May struggle with complex layouts.Simple HTML/CSS to PDF conversion tasks where JavaScript rendering is not needed.GoodLowBasicNoYesFreeModerate
python-pdfkitFast native conversion. Good CSS support via wkhtmltopdf. Reliable output.Limited JavaScript support. Requires wkhtmltopdf installation.Various HTML to PDF tasks requiring good CSS rendering but limited JavaScript execution.GoodMediumGoodLimitedYesFreeActive
PlaywrightCross-browser support, powerful automation capabilities, good performance. Modern API.Requires installation of browser binaries. Higher resource usage.Comprehensive testing and rendering of complex web pages, including those with dynamic content.GoodHighExcellentExcellentYesFreeVery Active
WeasyPrintExcellent CSS support. No external dependencies. Clean Python API.No JavaScript support. Installation can be complex on some systems.Static HTML/CSS documents requiring precise CSS rendering and layout control.GoodMediumExcellentNoYesFreeActive

In summary, the choice between Pyppeteer, xhtml2pdf, python-pdfkit, Playwright, and WeasyPrint depends on your project’s specific requirements.

Pyppeteer shines when dealing with dynamic content, thanks to its complete browser automation features. On the other hand, xhtml2pdf provides a simple Python-focused solution for basic conversions.

python-pdfkit, which builds upon wkhtmltopdf, sits as a flexible option in between. Developers should consider the features, setup intricacies, and performance of each library in relation to their project’s needs to make the right decision.

Playwright stands out for its cross-browser capabilities and powerful automation features, making it ideal for rendering complex and dynamic web pages.

WeasyPrint is excellent for static HTML/CSS documents requiring precise CSS rendering and layout control, but it lacks JavaScript support and can be complex to install on some systems.

Challenges with Large-Scale PDF Generation

While the methods above work for small-scale PDF generation, they can become problematic when dealing with thousands of PDFs or complex templates. Issues include:

  • Time-consuming and resource-intensive processing
  • Tedious template management and updates
  • Complex infrastructure for tracking and storing PDFs
  • Inconsistent rendering across systems

Common HTML to PDF Conversion Challenges

1. CSS Compatibility

  • Different libraries support varying levels of CSS
  • Solutions for handling complex layouts
  • Best practices for responsive designs

2. Performance Optimization

  • Memory management techniques
  • Batch processing strategies
  • Caching mechanisms

3. Enterprise Considerations

  • Scalability factors
  • Security considerations
  • Compliance requirements

Templated offers an API-based solution for efficient, large-scale PDF and Image generation, supporting JavaScript, CSS, and HTML rendering. It’s ideal for complex use cases and addresses the challenges of manual PDF generation methods.

Using Templated for PDF Generation

Templated allows you to design and manage your templates efficiently. After logging in, you’ll see your Dashboard where you can manage existing templates or create new ones:

From your Dashboard, you can design your own templates or customize an existing one from the Template Gallery. Below is the Certificate of Achievement Template you can use. There are 100+ free templates available that you can pick and customize to your needs.

To start using Templated API, you need to get your API key from the API Integration tab on your dashboard.

Now, let’s see how you can integrate your application with the API. In this example, we’ll use a certificate template to generate PDFs.

import requests
import json
# Initialize HTTP client
client = requests.Session()
# API URL
url = "https://api.templated.io/v1/render"
# Set headers
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer `${YOUR_API_KEY}`",
}
# Payload data
payload = {
"template": template_id,
"format": "pdf",
"modifications": [
{ "layer": "date", "text": "02/10/2024" }
{ "layer": "name", "text": "John Doe" }
{ "layer": "signature", "text": "Dr. Mark Brown" }
{
"layer": "details",
"text":
"This certificate is awarded to John Doe in recognition of their successful " +
"completion of Computer Sciente Degree on 02/10/2024."
}
],
}
# Serialize payload to JSON
json = json.dumps(payload)
# Make the POST request
response = client.post(url, data=json, headers=headers)
# Read the response
response = response.text
# Print the response
print(response)

and If we check response we have the following

{
"renderUrl": "PDF_URL",
"status": "success",
"template_id": "YOUR_TEMPLATE_ID"
}

In the code above, using Templated to convert HTML to PDF is pretty simple. No additional libraries need to be installed. You only need to make a single API call, providing your data as the request body. That’s all there is to it!

You can use the renderUrl from the response to download or distribute the generated PDF.

Note: If you’re looking for a comprehensive overview of Python libraries for PDF generation, including options beyond HTML conversion, be sure to check out our in-depth guide: Generate PDFs in Python with 6 Popular Libraries. This resource covers a wide range of tools and techniques to suit various PDF creation needs in Python.

Other languages

You you want to learn how to convert HTML to PDF in other languages here are other resources for you to explore:

Conclusion

PDF generation is now a standard part of every business application, and it shouldn’t be a source of stress for developers.

We’ve explored how to use third-party libraries for straightforward PDF generation. However, for more complex scenarios like template management, Templated offers a seamless solution through simple API calls to generate PDFs.

To get started, sign up for a free account and begin automating your PDFs today!

Automate your images and PDFs with a powerful API

Automate your marketing, social media visuals, banners, PDFs and more with our
 API and no-code integrations

Learn More
Back to Blog

Ready to start generating your images and PDFs?

Sign up to our free trial and try it for yourself

See our latest posts

View all posts »
How To Automate Job Posting Images for LinkedIn

How To Automate Job Posting Images for LinkedIn

Learn how to automate job posting images for LinkedIn using Templated, Google Sheets, and Zapier, saving time while keeping your visuals consistent.

How To Automate Instagram Posts using Google Sheets & Make

How To Automate Instagram Posts using Google Sheets & Make

Learn how to automate your Instagram posts using Templated and Google Sheets, saving time and ensuring a steady flow of engaging content for your audience.

How to Generate Images from Google Sheets with Zapier

How to Generate Images from Google Sheets with Zapier

Learn how to automate image generation using data from Google Sheets and Templated's powerful API with Zapier. This step-by-step guide will help you create a no-code workflow to streamline your visual content creation process.

How to Generate Images from Google Sheets with Make

How to Generate Images from Google Sheets with Make

Learn how to automate image generation using data from Google Sheets and Templated's powerful API with Make (formerly Integromat). This step-by-step guide will help you create a no-code workflow to streamline your visual content creation process.