# JavaScript HTML to PDF API

Call one POST from Node or any fetch runtime and the print-stable PDF comes back in the same response. The rendering happens on a real Chromium browser on our side, so your stack never hosts a headless browser, pins a Chromium version, or restarts a zombie renderer at 3am.

[Try it free without an account](https://webcapture.io/tools/url-to-pdf), or keep reading.

## Quick start

One POST. The connection is held until the file is ready; add `?wait=false` to get a ticket instead for async pickup.

```
import { writeFile } from "node:fs/promises";

const key = process.env.WC_KEY;
const res = await fetch("https://webcapture.io/v1/convert", {
  method: "POST",
  headers: { "Authorization": `Bearer ${key}`, "Content-Type": "application/json" },
  body: JSON.stringify({ url: "https://example.com/report" }),
});
const receipt = await res.json();
const pdf = await fetch(receipt.download, {
  headers: { "Authorization": `Bearer ${key}` },
});
await writeFile("report.pdf", Buffer.from(await pdf.arrayBuffer()));
```

The download keeps a legacy `.pdf` suffix for every format; the receipt's `download` field already points at the right URL. Same page covers [Java](https://webcapture.io/html-to-pdf-api-java) and [PHP](https://webcapture.io/html-to-pdf-api-php).

## Why not the library

Puppeteer in your own container works until it is your job: the Chromium binary per host, the version pin against your Node release cycle, the render workers that hang under load. This API is that worker, minus the babysitting. Any JavaScript runtime with `fetch` can call it; keep the key on the server side, because a key shipped to the browser is a key you published.

## The receipt, the ticket, and the poll

The quick start reads a receipt: the POST holds the connection and answers `200` with one JSON object: `id`, `bytes` (the finished document's size), `attempts` (the render passes used; a clean render reads 1), `remaining` (renders left on the monthly quota), `sourceUrl` and `sourceType`, and the key-scoped `download` URL. That hold is the right default for a render that takes a few seconds. When your caller cannot afford to block (a queue worker, a serverless function with an execution budget), add `?wait=false` and the endpoint answers `202` with a ticket instead: `{id, status: "queued", poll, download}`.

GET the ticket's `poll` URL with the same Authorization header, no faster than about once a second. The status walks `queued` to `rendering` to `ready`, or stops at `failed` with an `error` message in the body. The same poll response carries `attempts`, and `bytes` once the document exists. Renders usually finish in seconds rather than minutes; finished artifacts stay downloadable for at least seven days (30 on Scale), so the process that downloads does not have to be the one that queued. Prefer push to poll? A key with a `webhookUrl` gets a signed completion event on Pro and Scale, with the poll endpoint remaining the source of truth because webhook delivery is best-effort and can arrive twice.

```
const post = await fetch("https://webcapture.io/v1/convert?wait=false", {
  method: "POST",
  headers: { "Authorization": `Bearer ${key}`, "Content-Type": "application/json" },
  body: JSON.stringify({ url: "https://example.com/report" }),
});
if (post.status !== 202) throw new Error(`expected a ticket, got ${post.status}`);
let job = await post.json();

while (job.status === "queued" || job.status === "rendering") {
  await new Promise((r) => setTimeout(r, 1000)); // no faster than ~1 poll a second
  job = await (await fetch(job.poll, { headers: { Authorization: `Bearer ${key}` } })).json();
}
if (job.status === "failed") throw new Error(job.error);
```

## When the render refuses, the JSON names it

A refused call answers a JSON body with an `error` message, so the failure shows up in your logs as a sentence, not a status code alone. The four a Node service actually meets: `401` means the Authorization header is missing, wrong, or the key was revoked; check the header first, then the dashboard for revocations. `404` on a poll or download: the id belongs to another key's account, not that the render vanished; the receipt's `download` path appends `.pdf`, the poll path does not, so copy them as given. `422` means the request itself was rejected: a non-public URL (private and local addresses are refused), a body field out of range (the message names the field and its limit), or a pairing the endpoint refuses, such as `pageSize` on a `format` that is not pdf.

`429` splits into three kinds the body tells apart for you. The monthly quota wall carries `used`, `limit`, `resetDate`, and an `upgradeUrl`: nothing bills past quota, so the correct move is to wait for the month to turn over or follow the upgrade link. A full render queue or a rate-limited address instead carries `retryAfterSec`: wait that many seconds and resend the same request unchanged; the queue-full kind also sets a matching `retry-after` header. The third kind caps concurrent renders (1, 3, or 10 by tier): its body carries `code`, `feature`, `requiredTier`, and `upgradeUrl`, and the fix is to let an in-flight render finish; in the batch loop above, that means pacing the submit side until a ticket resolves. `502` is the page refusing to render: bot walls are the common cause; retry once later, and treat a target that keeps refusing as out of scope by design.

```
const res = await fetch("https://webcapture.io/v1/convert", { method: "POST", headers, body });
if (!res.ok) {
  const { error, ...detail } = await res.json(); // "error" always; 429s add fields
  if (res.status === 429 && detail.resetDate) {
    console.log(`quota ${detail.used}/${detail.limit} used, resets ${detail.resetDate}; nothing billed`);
  } else if (res.status === 429 && detail.retryAfterSec) {
    await new Promise((r) => setTimeout(r, detail.retryAfterSec * 1000)); // resend unchanged
  } else {
    throw new Error(`${res.status}: ${error}`);
  }
}
```

## Render controls

Checked 2026-11-12 against the API reference ([/docs](https://webcapture.io/docs)): `waitFor` selectors, `waitForNetwork`, `settle`, `colorScheme`, `blockAds`, `pageRanges`, custom `filename`, viewport sizing, and full-page by default. The honest limits list lives on the [main API page](https://webcapture.io/html-to-pdf-api). The knobs a PDF job reaches for, with the reference's own types and defaults:

| Parameter | Type | Default | What it does |
| --- | --- | --- | --- |
| `pageSize` | string | `A4` | Paper for the print: `A4`, `A3`, `Letter`, `Legal`, `A5`, matched case-insensitively. Anything off the list, or the field on a non-pdf `format`, answers 422. |
| `landscape` | boolean | false (portrait) | Turns the paper sideways; pdf only. |
| `pageRanges` | string | all pages | Digits, spaces, commas, hyphens: `"1-3,7"`. |
| `scale` | number | 1 | Print scaling, 0.1 to 2; pdf only. |
| `waitFor` | string | none | CSS selector (1 to 500 characters) the render waits for before printing, capped at min(`settle`, 10 seconds); a selector that never appears fails the render. |
| `settle` | integer ms | deployment default | Post-load wait, 0 to 10000. |
| `waitForNetwork` | boolean | off | Wait for a quiet network (networkidle) instead of the load event. |
| `colorScheme` | string | `light` | `light`, `dark`, or `site`; only moves pages that answer `prefers-color-scheme`. |
| `filename` | string | derived from the page | Download name, 1 to 100 characters of letters digits dot dash underscore; echoed on the receipt. |
| `blockAds` | boolean | false | Filter ad and tracker requests and hide leftover slots; best effort, and markdown gets network blocking only. |

Everything else the body accepts (headers and footers, tagged PDFs, watermark, metadata, encryption, `sandbox` quota-free test renders) is specified with the same exactness in the [convert body fields](https://webcapture.io/docs#convert-fields) table.

## Queue a batch, then poll it down

The hello-world renders one URL. The shape Node services actually run is a batch: a queue of URLs handed to the endpoint as tickets, polled down, and downloaded as each one turns ready. The tickets make the whole batch fire-and-forget at POST time: you queue twenty renders in under a second and spend the rest of the minute collecting, instead of twenty sequential holds.

```
import { writeFile } from "node:fs/promises";

const urls = ["https://example.com/invoice/1042", "https://example.com/invoice/1043", /* ... */];
const headers = { "Authorization": `Bearer ${key}`, "Content-Type": "application/json" };

const tickets = new Map();
for (const url of urls) {
  const res = await fetch("https://webcapture.io/v1/convert?wait=false", {
    method: "POST", headers, body: JSON.stringify({ url }),
  });
  if (res.status === 429) throw new Error(`quota or queue: ${JSON.stringify(await res.json())}`);
  const ticket = await res.json(); // 202 {id, status: "queued", poll, download}
  tickets.set(ticket.id, ticket);
}

while (tickets.size > 0) {
  await new Promise((r) => setTimeout(r, 1000));
  for (const [id, job] of [...tickets]) {
    const poll = await (await fetch(job.poll, { headers: { Authorization: `Bearer ${key}` } })).json();
    if (poll.status === "ready") {
      const pdf = await fetch(poll.download, { headers: { Authorization: `Bearer ${key}` } });
      await writeFile(`out/${id}.pdf`, Buffer.from(await pdf.arrayBuffer()));
      tickets.delete(id);
    } else if (poll.status === "failed") {
      console.error(`${id} failed after ${poll.attempts} attempt(s): ${poll.error}`);
      tickets.delete(id);
    }
  }
}
```

Three details worth copying. The download repeats the Authorization header: the URL is key-scoped, and without it the GET answers 401. A failed ticket is terminal and costs no quota: only completed renders count, so the loop can drop it and move on. And the free tier holds 1 render in flight, Pro 3, Scale 10: a 429 whose body names `feature` and `requiredTier` is the concurrency cap, not the quota, and the fix is to pace the queue, not to panic about billing.

## Three questions, answered

### Do I need Puppeteer installed?

No. The rendering happens on this side, in a real Chromium, and your code is one `fetch` call: Node 18+ has it in the standard library, and so do Bun, Deno, and every runtime that speaks fetch. Nothing native to compile, no browser binary to download at build time, and no Chromium version to pin in CI. The trade is equally plain: you do not get Puppeteer's in-page handles, so anything you would have done with `page.evaluate` is instead done by the page itself (an inline `javascript` body field exists for exactly that) or not at all.

### What does `wait` wait for?

The HTTP connection, not the page. `wait=true` (the default) holds the POST open until the finished document is ready to stream back; `wait=false` hands you the 202 ticket immediately and the waiting moves to your poll loop. It says nothing about how long the page itself is given: that is the job of `waitFor` (a selector to appear), `settle` (post-load milliseconds), and `waitForNetwork` (a quiet network instead of the load event), each capped by the same 10-second budget.

### Can I render locally hosted pages?

Not over the public API. Targets must be public http(s) URLs; private and local addresses are refused with 422, and so is anything that resolves to a private IP after DNS. That is the same SSRF admission the endpoint applies to every asset the page loads, and it is why `localhost`, staging behind a VPN, and `192.168.x.x` hosts all bounce. The escape hatch belongs to self-hosting, not to a flag on a public call: an operator sets `WC_ALLOW_PRIVATE_TARGETS=1` on their own deployment. For staging pages, put them on a public HTTPS host or send the HTML directly: the `html` body field takes raw markup with an optional public `baseUrl` for relative assets.

Pricing: Free 50 renders a month, Pro $19 for 5,000, Scale $69 for 35,000. Terms on [pricing](https://webcapture.io/pricing); more reading in the [HTML to PDF guides](https://webcapture.io/guides).

## Render your first page in seconds

Mint a key, POST a URL, and the finished document comes back in the same response; pass ?wait=false for a job ticket with poll and download URLs. The first 50 renders a month are free, and there is no credit card. Not ready for a key? The free [URL to PDF tool](https://webcapture.io/tools/url-to-pdf) renders public pages without one.