In this guide you'll learn how to convert HTML to PDF in Python using the HTML2PDF REST API. We'll cover:

  • Converting a URL to PDF with Python
  • Converting raw HTML to PDF
  • Setting page size, orientation and layout options
  • Handling errors and status codes

The HTML2PDF API accepts both URLs and HTML and returns a ready-to-download PDF document. You just send a simple HTTP GET or POST request to https://api.html2pdf.co.uk/ with your license key and parameters.


Prerequisites

  • Python 3.7 or higher
  • requests library (pip install requests)
  • An HTML2PDF license key (free trial available)

1. Convert a URL to PDF in Python

The easiest way to create a PDF is to convert an existing URL. HTML2PDF exposes a single endpoint:

https://api.html2pdf.co.uk/?license=YOUR_LICENSE_KEY&url=URL_TO_CONVERT

Here's a complete example using requests:

import requests

API_ENDPOINT = "https://api.html2pdf.co.uk/"
LICENSE_KEY = "yourlicensekey"  # replace with your real license

def url_to_pdf(source_url: str, output_path: str) -> None:
    params = {
        "license": LICENSE_KEY,
        "url": source_url,
    }

    # stream the response so we don't load the entire PDF in memory first
    with requests.get(API_ENDPOINT, params=params, stream=True, timeout=60) as r:
        r.raise_for_status()  # raises an HTTPError if the status is not 200
        with open(output_path, "wb") as f:
            for chunk in r.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)

if __name__ == "__main__":
    url_to_pdf("https://example.com/invoice/123", "invoice-123.pdf")
    print("PDF created!")

In this example:

  • license carries your HTML2PDF license key.
  • url is the page you want to convert.
  • The API returns the PDF binary directly if the conversion is successful.
Tip: Set your default layout options (page size, margins, header/footer, etc.) once in the members area. You can then keep your Python code very simple and override options only when needed.

2. Convert raw HTML to PDF in Python

Sometimes you don't have a public URL and want to convert dynamically generated HTML instead (for example, invoices or reports). In that case use the html parameter instead of url:

import requests

API_ENDPOINT = "https://api.html2pdf.co.uk/"
LICENSE_KEY = "yourlicensekey"

def html_to_pdf(html: str, output_path: str) -> None:
    payload = {
        "license": LICENSE_KEY,
        "html": html,
    }

    # Using POST: requests will handle form-encoding the data for us
    with requests.post(API_ENDPOINT, data=payload, stream=True, timeout=60) as r:
        r.raise_for_status()
        with open(output_path, "wb") as f:
            for chunk in r.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)

if __name__ == "__main__":
    html = """
    <html>
      <head><title>Sample invoice</title></head>
      <body>
        <h1>Invoice #123</h1>
        <p>Thanks for your order!</p>
      </body>
    </html>
    """
    html_to_pdf(html, "invoice-123.pdf")

When you pass HTML, make sure it is complete and valid (with <html>, <head>, <body> tags), so the rendering engine can lay it out correctly.


3. Setting page size and layout options

You can control the output by adding extra parameters to the API call, for example:

  • page_size (e.g. A4, Letter)
  • orientation (portrait or landscape)
  • css_media_type (screen or print)
  • lazy_load and wait_time for JS-heavy pages

Here's a Python example that sets some options:

import requests

API_ENDPOINT = "https://api.html2pdf.co.uk/"
LICENSE_KEY = "yourlicensekey"

def url_to_pdf_with_options(source_url: str, output_path: str) -> None:
    params = {
        "license": LICENSE_KEY,
        "url": source_url,
        "page_size": "A4",
        "orientation": "portrait",
        "css_media_type": "print",
        "lazy_load": "true",
        "wait_time": "3000",  # milliseconds
        "title": "Invoice PDF",
        "filename": "invoice-123.pdf",
    }

    with requests.get(API_ENDPOINT, params=params, stream=True, timeout=60) as r:
        r.raise_for_status()
        with open(output_path, "wb") as f:
            for chunk in r.iter_content(chunk_size=8192):
                if chunk:
                    f.write(chunk)

All available options are documented in detail on the API documentation page.


4. Error handling and status codes

When something goes wrong, the API returns an HTTP status code instead of a PDF. The most important ones are:

CodeDescription
200 OKconversion succeeded and the body contains a PDF
400 Bad Requestyou did not pass a URL or HTML
401 Authorization requiredinvalid or missing license key
429 Too Many Requestsyou exceeded your plan's limit
504 / 599timeout issues with the target URL

These are documented in the Return Codes section of the API docs.

In Python, it's straightforward to check:

r = requests.get(API_ENDPOINT, params=params, stream=True, timeout=60)

if r.status_code == 200:
    # write PDF to disk
    ...
elif r.status_code == 400:
    raise ValueError("No URL or HTML provided to HTML2PDF API")
elif r.status_code == 401:
    raise PermissionError("Invalid HTML2PDF license key")
else:
    raise RuntimeError(f"HTML2PDF API error: {r.status_code} - {r.text[:200]}")

5. Next steps

You now know how to convert HTML to PDF in Python using the HTML2PDF API. Next, you might want to: