# PHP HTML to PDF API

One POST from any PHP runtime hands the URL to a real Chromium renderer and the print-stable PDF lands in the same response. Dompdf keeps the invoice workloads going, but grid layout and modern CSS are where it stops; here the CSS engine is Chromium and your PHP is one HTTP call.

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

## Quick start

Works on any PHP 8 with cURL. One call holds the connection until the file is ready; pass `?wait=false` to get the async ticket instead.

```
<?php
$key = getenv('WC_KEY');
$ch = curl_init('https://webcapture.io/v1/convert');
curl_setopt_array($ch, [
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    'Authorization: Bearer ' . $key,
    'Content-Type: application/json',
  ],
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => json_encode(['url' => 'https://example.com/report']),
]);
$receipt = json_decode(curl_exec($ch), true);
$fp = fopen('report.pdf', 'w');
$dl = curl_init($receipt['download']);
curl_setopt_array($dl, [
  CURLOPT_FILE => $fp,
  CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $key],
]);
curl_exec($dl);
fclose($fp);
```

The receipt's `download` field ends in a legacy `.pdf` suffix whatever the format; use it unchanged. The same endpoint covers [JavaScript](https://webcapture.io/html-to-pdf-api-javascript) and [Java](https://webcapture.io/html-to-pdf-api-java).

## Why not the library

Dompdf, mPDF, and snappy render with their own CSS engines, and each one draws the line somewhere a real invoice lives: grid layout, variable fonts, or a print stylesheet a client shipped last week. Self-hosted headless Chromium from PHP means supervising a binary per worker. Here Chromium is ours and current, and the PHP stays an HTTP call with cURL, which every PHP deployment already has.

## A receipt, a ticket, and a poll loop

The quick start's 200 answer is one JSON receipt, read field by field: `id` names the conversion for every later call; `bytes` reports the finished document's size; `attempts` counts the render passes (1 on a clean run); `remaining` shows what is left of the monthly quota; `sourceUrl` and `sourceType` echo the admitted source; and `download` is the key-scoped GET that carries the bytes. A PHP-FPM worker should not sit on that hold when it does not have to: add `?wait=false` and the endpoint answers `202` with a ticket instead (`{id, status: "queued", poll, download}`), so the request finishes in milliseconds and the waiting moves somewhere that can afford it: a cron, a queue worker, a follow-up request.

Fetch the poll URL with the same Authorization header, spacing polls about a second apart. The status runs `queued`, then `rendering`, then `ready`; a failed status stops the walk and carries the render's `error` message, next to `attempts` and, once ready, `bytes`. Renders usually finish in seconds rather than minutes, and a finished artifact stays downloadable for at least seven days (30 on Scale), long enough for tonight's cron run and tomorrow's to share the work. A key with a `webhookUrl` can instead receive a signed completion event (Pro and Scale), with the poll endpoint remaining the source of truth because webhook delivery is best-effort and can arrive twice.

```
$post = curl_init('https://webcapture.io/v1/convert?wait=false');
curl_setopt_array($post, [
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $key, 'Content-Type: application/json'],
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => json_encode(['url' => 'https://example.com/report']),
]);
$ticket = json_decode(curl_exec($post), true); // 202: {id, status: "queued", poll, download}

do {
  sleep(1); // no faster than ~1 poll a second
  $poll = curl_init($ticket['poll']);
  curl_setopt_array($poll, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $key],
  ]);
  $receipt = json_decode(curl_exec($poll), true);
  curl_close($poll);
} while (in_array($receipt['status'], ['queued', 'rendering'], true));

if ($receipt['status'] === 'failed') {
  throw new RuntimeException($receipt['error']); // the render's own failure message
}
```

## When the render refuses

Every refusal is a JSON body with an `error` message, which is what turns a failed render from a mystery into a log line. `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 means the id belongs to another key's account; the receipt's `download` path appends `.pdf` and the poll path does not, so copy both as given. `422` means the request 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 refused pairing such as `pageSize` on a non-pdf `format`.

`429` arrives in three shapes. The monthly quota wall carries `used`, `limit`, `resetDate`, and an `upgradeUrl`, and nothing bills past quota: wait for the month to turn over or follow the upgrade link. A full render queue or a rate-limited address carries `retryAfterSec`, and the queue-full kind adds a matching `retry-after` header: sleep that many seconds and resend the same request unchanged. The third shape is the in-flight cap (1, 3, or 10 concurrent renders by tier): its body names `code`, `feature`, `requiredTier`, and `upgradeUrl`, with no reset date and no wait count, and the documented next step is to wait for an in-flight render to finish rather than resend into a full slot. `502` means the page refused to render; bot walls are the common cause, one retry later is reasonable, and a target that keeps refusing is out of scope by design.

```
$status = curl_getinfo($post, CURLINFO_RESPONSE_CODE);
$body = json_decode(curl_exec($post), true);
if ($status === 429) {
  if (isset($body['resetDate'])) {
    // quota wall: used, limit, resetDate, upgradeUrl; nothing billed
    error_log("quota {$body['used']}/{$body['limit']} used, resets {$body['resetDate']}");
  } elseif (isset($body['retryAfterSec'])) {
    sleep((int) $body['retryAfterSec']); // queue-full: resend the same request unchanged
  } else {
    // concurrency cap: code, feature, requiredTier, upgradeUrl; wait for an in-flight render to finish
  }
} elseif ($status >= 400) {
  throw new RuntimeException($status . ': ' . $body['error']);
}
```

## Render controls

The list below was checked 2026-11-12 against the API reference ([/docs](https://webcapture.io/docs)): `waitFor` selectors, `waitForNetwork`, `settle`, `colorScheme`, `blockAds`, `pageRanges`, custom `filename`, and full-page by default. For what the endpoint will not do, the [main API page](https://webcapture.io/html-to-pdf-api) carries the honest-limits list. For the reference's own types and defaults, the knobs a PHP job reaches for:

| Parameter | Type | Default | What it does |
| --- | --- | --- | --- |
| `pageSize` | string | `A4` | Paper for the print: `A4`, `A3`, `Letter`, `Legal`, `A5`, matched case-insensitively. 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) to wait for before printing, capped at min(`settle`, 10 seconds); one 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 and carried by the download's Content-Disposition header. |
| `blockAds` | boolean | false | Filter ad and tracker requests and hide leftover slots; best effort. |

The body takes more than the table shows: headers and footers, tagged PDFs, watermark, metadata, encryption, and quota-free `sandbox` test renders are specified with the same exactness in the [convert body fields](https://webcapture.io/docs#convert-fields) table.

## The nightly report

The hello-world renders one page when asked. The job PHP deployments actually run is the scheduled report: a cron entry fires a script at a fixed hour, the script renders the same URL, names the file so the archive sorts itself, and leaves the bytes where the ops dashboard expects them. Nothing in that loop needs a browser on the host: the render is one POST and the file is one GET, and `filename` is what turns a pile of `cnv_` ids into an archive a human can browse.

```
<?php
// crontab: 0 2 * * * php /opt/reports/nightly.php
$key = getenv('WC_KEY');
$day = date('Y-m-d');
$body = json_encode([
  'url' => 'https://example.com/kpi/dashboard',
  'pageSize' => 'A4',
  'landscape' => true,
  'filename' => "kpi-report-{$day}",
]);

$ch = curl_init('https://webcapture.io/v1/convert');
curl_setopt_array($ch, [
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $key, 'Content-Type: application/json'],
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => $body,
]);
$receipt = json_decode(curl_exec($ch), true);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
curl_close($ch);
if ($status !== 200) { exit(1); } // see "When the render refuses" above

$dl = curl_init($receipt['download']); // receipt already carries the filename you chose
curl_setopt_array($dl, [
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . $key],
]);
file_put_contents("/var/reports/kpi-report-{$day}.pdf", curl_exec($dl));
```

Two habits make the cron trustworthy. Log the receipt's `id` and `attempts` next to the file: a report whose `attempts` reads 3 took three render passes, and a support question about that night's numbers has an answer waiting. And keep the free tier's shape in mind: 50 renders a month covers a nightly report with room to spare, but a 429 naming `resetDate` means the account's other jobs already spent the quota, and the report moves to tomorrow's run rather than billing anyone anything.

## When to pick the PHP route

Same endpoint, three reasonable homes. The honest division of labor:

| If your world looks like | Pick | Why |
| --- | --- | --- |
| Cron owns the schedule | PHP | The nightly-report pattern above is the whole integration: one script, cURL, no daemon to keep alive between runs. |
| A legacy WordPress or Laravel stack renders documents today | PHP | Swap the Dompdf or snappy call for the POST; templates stay templates, and grid layout, variable fonts, and last week's client CSS stop being the breaking line. |
| The team lives in Node or the JVM | [JavaScript](https://webcapture.io/html-to-pdf-api-javascript) / [Java](https://webcapture.io/html-to-pdf-api-java) | The same endpoint and byte-identical receipts; each sibling page shows the batch and the behind-login patterns in its own language. |

Every route reads the same receipt and refuses with the same JSON, so moving a report job from one of these languages to another rewrites the call site, not the integration.

On price: the free tier renders 50 a month, Pro is $19 for 5,000, Scale $69 for 35,000. The [pricing page](https://webcapture.io/pricing) holds the full terms; the [HTML to PDF guides](https://webcapture.io/guides) hold more reading.

## 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.