DocuHook

Guides · python html to pdf without weasyprint

Python HTML to PDF Without WeasyPrint or Playwright

2026-11-17 · 7 min read

If you searched for Python HTML to PDF without WeasyPrint or Playwright, you have probably met one of these:

  • OSError: cannot load library 'pango-1.0-0' (or gobject-2.0-0) — WeasyPrint needs Pango installed at the OS level
  • playwright install chromium that will not run in your slim Docker image or on your PaaS
  • pdfkit failing with No wkhtmltopdf executable found — and wkhtmltopdf itself is archived
  • Container images that grew by hundreds of MB just to print an invoice

This guide shows a FastAPI and a Flask endpoint that turn JSON + an HTML template into a PDF with one HTTPS request — no system packages, no browser, nothing beyond an HTTP client in requirements.txt.

When you should keep WeasyPrint

Be honest about the trade-off first. WeasyPrint has stronger CSS Paged Media support (page counters, running headers, @page margin boxes) than Dompdf, which is what DocuHook renders with. If you rely on those and can install Pango, keep WeasyPrint. If you need exactly what Chrome prints, Playwright is the reference.

DocuHook fits when the document is an invoice, receipt, certificate, or report built from tables and blocks — and you would rather not own a rendering stack inside your Python image.

How the call works

POST https://docuhook.com/api/v1/render
Authorization: Bearer dh_…
Content-Type: application/json

{ "mode": "sync", "data": { … }, "html": "<h1>Invoice {{invoice.number}}</h1>", "filename": "invoice.pdf" }

→ 200 application/pdf. The response body is the PDF. Tokens are {{path.to.value}}; values are HTML-escaped on merge.

1. Template file

Save as templates/invoice.html. The <!--ROWS--> marker is where line items go:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
  body { font-family: "DejaVu Sans", sans-serif; margin: 40px; font-size: 13px; color: #111; }
  table { width: 100%; border-collapse: collapse; margin-top: 20px; }
  th, td { padding: 8px 0; border-bottom: 1px solid #ddd; text-align: left; }
  .num { text-align: right; }
</style>
</head>
<body>
  <h1>Invoice {{invoice.number}}</h1>
  <p>{{invoice.date}} · {{customer.name}}</p>
  <table>
    <thead><tr><th>Item</th><th class="num">Qty</th><th class="num">Total</th></tr></thead>
    <tbody>
      <!--ROWS-->
    </tbody>
  </table>
  <p class="num"><strong>Total {{currency}} {{total}}</strong></p>
</body>
</html>

Jinja gotcha: {{customer.name}} is also Jinja syntax. Read this file with plain open() / Path.read_text(), not through render_template or Jinja2Templates, or Jinja will try to fill the tokens itself. (Prefer Jinja for everything? Render the full HTML yourself and send "data": {} — DocuHook then only does the PDF step.)

2. Build line-item rows

Templates have no loops. Expand rows before the call using indexed tokens, so DocuHook still fills and escapes each value:

from pathlib import Path

TEMPLATE = Path("templates/invoice.html").read_text(encoding="utf-8")

def with_rows(template: str, items: list[dict]) -> str:
    rows = "\n".join(
        f'<tr><td>{{{{items.{i}.name}}}}</td>'
        f'<td class="num">{{{{items.{i}.qty}}}}</td>'
        f'<td class="num">{{{{currency}}}} {{{{items.{i}.total}}}}</td></tr>'
        for i in range(len(items))
    )
    return template.replace("<!--ROWS-->", rows)

In an f-string, {{{{ produces a literal {{, so row 0 becomes <tr><td>{{items.0.name}}</td>….

3. FastAPI endpoint

pip install fastapi uvicorn httpx
import os
import httpx
from fastapi import FastAPI, HTTPException
from fastapi.responses import Response

app = FastAPI()
DOCUHOOK_URL = "https://docuhook.com/api/v1/render"

@app.post("/invoice")
async def invoice(order: dict):
    payload = {
        "mode": "sync",
        "data": order,  # {"invoice": {...}, "customer": {...}, "items": [...], "currency": "EUR", "total": "120.00"}
        "html": with_rows(TEMPLATE, order.get("items", [])),
        "filename": f"invoice-{order['invoice']['number']}.pdf",
    }
    async with httpx.AsyncClient(timeout=30) as client:
        r = await client.post(
            DOCUHOOK_URL,
            json=payload,
            headers={
                "Authorization": f"Bearer {os.environ['DOCUHOOK_API_KEY']}",
                "Accept": "application/pdf",
            },
        )
    if r.status_code != 200:
        raise HTTPException(status_code=502, detail=r.text)

    return Response(
        content=r.content,
        media_type="application/pdf",
        headers={"Content-Disposition": f'attachment; filename="{payload["filename"]}"'},
    )

Run it with uvicorn main:app --reload and POST an order to /invoice — you get a downloadable PDF.

4. Flask endpoint

pip install flask requests
import os
import requests
from flask import Flask, Response, request, abort

app = Flask(__name__)

@app.post("/invoice")
def invoice():
    order = request.get_json()
    r = requests.post(
        "https://docuhook.com/api/v1/render",
        json={
            "mode": "sync",
            "data": order,
            "html": with_rows(TEMPLATE, order.get("items", [])),
            "filename": "invoice.pdf",
        },
        headers={
            "Authorization": f"Bearer {os.environ['DOCUHOOK_API_KEY']}",
            "Accept": "application/pdf",
        },
        timeout=30,
    )
    if r.status_code != 200:
        abort(502, r.text)
    return Response(
        r.content,
        mimetype="application/pdf",
        headers={"Content-Disposition": 'attachment; filename="invoice.pdf"'},
    )

What about the official Python client?

pip install docuhook-client gives you from docuhook import Client. Its render(), hook_render(), job_status(), and job_result() speak JSON, so render() returns the merged HTML in result["html"] — the opt-in "format": "html" path. Use it when you want HTML (to show a preview or convert elsewhere); use the direct request above when you want the PDF file.

Background jobs and webhooks

For Celery/RQ tasks or inbound webhooks, queue the render instead of waiting: send "mode": "async" (or Prefer: respond-async) and DocuHook answers 202 with job_id, status_url, and result_url. Later, GET the result_url with Accept: application/pdf — 202 means pending, 200 is the PDF. The Stripe and Shopify guides show the full pattern; the HTTP calls translate one-to-one to httpx.

Dompdf caveat

The PDF engine is Dompdf. Tables, borders, colors, images, and the bundled DejaVu fonts work well. Flexbox and grid do not, and advanced paged-media CSS is limited compared with WeasyPrint. If a layout must match Chrome exactly, request "format": "html" and convert it somewhere Chrome already runs.

Checklist

  • No weasyprint, pdfkit, or playwright in requirements — just httpx or requests
  • Template read as plain text, not through Jinja
  • Rows expanded with indexed tokens before the call
  • DOCUHOOK_API_KEY from the environment, never sent to the browser
  • Free plan: 100 PDFs/month with a watermark — plans for more

Related guides

The 3-line fix

r = httpx.post("https://docuhook.com/api/v1/render", json={"data": order, "html": html, "filename": "invoice.pdf"}, headers={"Authorization": f"Bearer {key}"}, timeout=30)
r.raise_for_status()
Path("invoice.pdf").write_bytes(r.content)  # application/pdf — no Pango, no Chromium

Try it in the live sandbox (no signup), read the API docs, or get an API key.