Docs / Reference / HTML to PDF in Python and Node.js

Docs menu · HTML to PDF in Python and Node.js

Reference

HTML to PDF in Python and Node.js

Render a document, wait for it to finish and read its warnings with typed Python and Node clients. Both retry temporary errors, download the PDF and encode your files for you.

Install

The client package files come with your preview key email. Publication on PyPI as stolid-client and on npm as @stolidhq/client is coming soon. Python needs version 3.12 or newer, Node.js version 20 or newer.

The Python client has one dependency, httpx, and is typed. The Node client has no dependencies and ships TypeScript types. Run these commands from the folder that contains the package file.

Terminal
python3 -m venv .venv && . .venv/bin/activate
pip install ./stolid_client-*.whl
Terminal
npm init -y
npm install ./stolidhq-client-*.tgz

The Node package is an ES module: use import in a .mjs file, or set "type": "module" in your package.json.

Configure

Both clients send requests to https://api.stolid.dev and read your API key from the STOLID_API_KEY environment variable. Set it again in every new terminal:

Terminal
export STOLID_API_KEY="stolid_live_…"

You can also pass the key to the constructor: StolidClient(api_key="...") in Python, where every argument is keyword-only, and new StolidClient({ apiKey: '...' }) in Node. Read the key from the environment or a secret store; do not write it in your code.

Your first PDF

Save this as hello.py and run python hello.py:

Python
from stolid_client import StolidClient

with StolidClient() as client:
    render = client.create_pdf(
        '<h1 style="font-family: sans-serif">Hello from Stolid</h1>',
        options={"format": "A4"},
    )
    with open("hello.pdf", "wb") as f:
        f.write(client.download_pdf(render))
    for warning in render.warnings:  # the render report
        print(warning.code, warning.message)

Save this as hello.mjs and run node hello.mjs:

Node
import { writeFile } from 'node:fs/promises';
import { StolidClient, getWarnings } from '@stolidhq/client';

const client = new StolidClient(); // reads STOLID_API_KEY

const render = await client.createPdf('<h1 style="font-family: sans-serif">Hello from Stolid</h1>', {
  options: { format: 'A4' },
});
await writeFile('hello.pdf', await client.downloadPdf(render));
for (const w of getWarnings(render)) console.warn(w.code, w.message); // the render report

After the script finishes, open hello.pdf. It prints a line for each warning, or nothing if there are none. create_pdf and createPdf wait for a running render, up to 120 seconds by default, and raise an error if the render fails.

Python also has an asyncio client, AsyncStolidClient, with the same methods; call them with await.

Send your own files

Give each file a relative name such as style.css or images/logo.png (no leading /) and use that same name in your HTML. Each file is bytes, {"text": "..."} (Python) or { text: '...' } (Node), or already base64-encoded content in base64. The client encodes everything for you.

Python
from stolid_client import StolidClient

html = """
<link rel="stylesheet" href="style.css">
<h1>Invoice #1042</h1>
"""
with StolidClient() as client:
    render = client.create_pdf(
        html,
        assets={"style.css": {"text": "h1 { font-family: Inter, sans-serif; color: #1f4e79; }"}},
    )
Node
const render = await client.createPdf('<link rel="stylesheet" href="style.css"><h1>Invoice #1042</h1>', {
  assets: { 'style.css': { text: 'h1 { font-family: Inter, sans-serif; color: #1f4e79; }' } },
});

Files and fonts covers fonts and scripts. options takes the API's own names; see Page options.

Methods

PythonNodeReturns
create_pdf(html, *, options, assets, idempotency_key, wait, timeout_s)createPdf(html, { options, assets, idempotencyKey, wait, timeoutMs, response })Returns the finished render by default. Set wait=False in Python or wait: false in Node to return the initial result, which may still be running
create_pdf_bytes(html, ...)createPdf(html, { response: 'binary' })The PDF itself, with the render ID and the warning count
get_render(render_id)getRender(id)The render as it is now
wait_for_render(render_or_id, ...)waitForRender(id, ...)The render once it is finished. Node returns either final status. Python raises on failure by default; pass raise_on_failure=False to return the failed render
download_pdf(render_or_id)downloadPdf(render)The PDF bytes
get_usage()getUsage()Renders this month, the limit and the mode
render.warningsgetWarnings(render)The list of warnings, empty when there are none

Results and the render report

Every render has id and status (running, succeeded or failed). Successful renders also have pdf_url, manifest and usage; failed renders have error with a code and message. The warnings are in manifest.warnings. Each has a code, a message and, for some codes, a sample. The codes are in Warning codes. New codes may appear later: unknown codes arrive as plain strings, so they never cause a parsing error.

Errors and retries

API and transport errors use StolidError and expose a code. Python has typed subclasses for server errors such as QuotaExceededError and client-side errors such as RenderWaitTimeoutError. Invalid Python arguments or render states can raise ValueError or TypeError. The Node client rejects with one StolidError class, and you read its code.

Python
from stolid_client import QuotaExceededError, RenderWaitTimeoutError, StolidError

try:
    render = client.create_pdf(html)
except QuotaExceededError:
    print("This month's renders are used up.")
except RenderWaitTimeoutError as err:
    render = client.wait_for_render(err.render_id, timeout_s=300)  # still rendering: keep waiting
except StolidError as err:
    print(err.code, err.status, err.render_id, err.message)
Node
import { StolidError } from '@stolidhq/client';

try {
  render = await client.createPdf(html);
} catch (err) {
  if (!(err instanceof StolidError)) throw err;
  if (err.code === 'QUOTA_EXCEEDED') console.error("This month's renders are used up.");
  else console.error(err.code, err.status, err.renderId, err.message);
}

The clients retry network errors, timeouts and HTTP 429, 500, 502, 503 and 504 for you, with capped exponential backoff, and honour a Retry-After header. They never retry 400, 401, 402, 404, 409, 413 or 422. A create response with error.render_id stops automatic retries.

Every create call sends an Idempotency-Key, yours or a generated one, and all retries of one call reuse it. Stolid remembers a key for 24 hours: the same key with the same content returns the original render instead of making a second one. Pass your own key when your program might repeat the call itself, for example a job that is re-run, and derive it from the document, such as invoice-42-v3. The limits and errors page lists every error code.

Usage

Python
usage = client.get_usage()
print(f"{usage.renders} of {usage.limit} renders used this month ({usage.mode} mode), {usage.remaining} left")
Node
const usage = await client.getUsage();
console.log(`${usage.renders} of ${usage.limit} renders used this month (${usage.mode} mode)`);

Live and test keys are counted separately. Failed renders are not counted.

Keeping your key safe

Keep your API key in an environment variable or a secret store, and call Stolid from your server, not from a browser or mobile app. A pdf_url is a time-limited link that anyone who holds it can use, so do not log or share it. The clients keep both the key and the link out of their printed output.

Public preview: free while we work with early users. Use sample data; there is no uptime commitment yet.