New: PDF to E-Invoice for Factur-X/ZUGFeRD, and PDF to PDF/A for archive-ready PDF/A-3b.

Convert HTML to PDF in Python with PDF.co

8 Minutes Read

In this tutorial, you will learn how to read a local HTML file, send its contents to PDF.co, and save the returned PDF on your computer. This example uses Python’s standard library, so no additional Python packages are required.

Step 1: Prepare your files and API key

Take the sample code below and save them as convert_html.py and sample.html into the same folder. Use Python 3.9 or later and set the PDFCO_API_KEY environment variable to your PDF.co API key.

The sample contains inline CSS and a small service report. Local image and stylesheet paths are not uploaded with the HTML; keep this first example self-contained.

convert_html.py

"""Convert a small local HTML file using PDF.co; Python 3.9+, no packages."""
import argparse
import json
import os
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import urlparse
from urllib.request import Request, urlopen

ENDPOINT = "https://api.pdf.co/v1/pdf/convert/from/html"


def convert(source, destination, api_key):
    if not api_key.strip():
        raise ValueError("Set PDFCO_API_KEY before running this example.")
    source, destination = Path(source), Path(destination)
    if source.resolve() == destination.resolve():
        raise ValueError("Input and output must be different files.")
    payload = {
        "html": source.read_text(encoding="utf-8"),
        "name": destination.name,
        "paperSize": "A4",
        "orientation": "Portrait",
        "margins": "20px 20px 20px 20px",
        "printBackground": True,
        "async": False,
    }
    request = Request(ENDPOINT, data=json.dumps(payload).encode("utf-8"),
                      headers={"x-api-key": api_key, "Content-Type": "application/json"})
    with urlopen(request, timeout=60) as response:
        result = json.load(response)
    if result.get("error") is not False:
        raise ValueError("PDF.co rejected conversion; check your account API logs.")
    result_url = result.get("url", "")
    if not isinstance(result_url, str) or urlparse(result_url).scheme != "https":
        raise ValueError("PDF.co did not return an HTTPS download URL.")
    # Do not forward the API key to the output-storage host.
    with urlopen(result_url, timeout=60) as response:
        pdf = response.read()
    if not pdf.startswith(b"%PDF-"):
        raise ValueError("Downloaded content does not have a PDF signature.")
    # Exclusive creation prevents accidental overwriting of an existing output.
    with destination.open("xb") as output:
        output.write(pdf)
    return len(pdf)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", type=Path)
    parser.add_argument("output", type=Path)
    args = parser.parse_args()
    if args.output.exists():
        parser.exit(1, "Output already exists; choose a new filename.\n")
    try:
        size = convert(args.input, args.output, os.environ.get("PDFCO_API_KEY", ""))
    except HTTPError as exc:
        parser.exit(1, f"HTTP {exc.code}; check API logs or output-link expiry.\n")
    except (OSError, ValueError, URLError) as exc:
        parser.exit(1, f"Conversion failed: {exc}\n")
    print(f"Saved {args.output} ({size} bytes; PDF signature checked).")


if __name__ == "__main__":
    main()

sample.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Weekly service report</title>
  <style>
    body { font-family: Arial, sans-serif; color: #203044; }
    h1 { background: #e6f2ff; padding: 16px; }
    table { width: 100%; border-collapse: collapse; }
    th, td { border: 1px solid #aab6c4; padding: 12px; text-align: left; }
    th { background: #e6f2ff; }
  </style>
</head>
<body>
  <h1>Weekly service report</h1>
  <p>Reference: HTML-PDF-001</p>
  <p>Customer: Café Example</p>
  <table>
    <tr><th>Service</th><th>Hours</th></tr>
    <tr><td>Design review</td><td>3</td></tr>
    <tr><td>Implementation</td><td>5</td></tr>
  </table>
  <p>Total: 8 hours</p>
</body>
</html>

Step 2: Configure the conversion

The script reads the HTML as UTF-8 and requests an A4 portrait PDF with background colors enabled. Adjust paperSize, orientation, and margins in the script as needed.

Step 3: Run the example

From that folder, run:

python3 convert_html.py sample.html report.pdf

Step 4: Check the saved PDF

On success, the script prints the saved filename and byte count. Open report.pdf and check for:

  • “Weekly service report” and reference HTML-PDF-001.
  • The accented customer name “Café Example.”
  • Two service rows and “Total: 8 hours.”
  • Light-blue heading backgrounds and readable table borders.

The script checks HTTP failures, API errors, and the downloaded file’s PDF signature. A signature check alone does not establish correct rendering.

If authentication fails, check your API key. If conversion times out, use the documented asynchronous workflow. Save the result promptly because output download links expire.

And that’s all there is to it. The input HTML string was converted to PDF with no extra work on our end, since the PDF.co API handled the entire conversion.

To review your API activity, check the request/response log. It shows the full details of each call, including the credits used and the estimated cost.

Related Tutorials

See Related Tutorials