# Java HTML to PDF API

One POST from any JVM language sends the URL to a real Chromium renderer and the print-stable PDF comes back in the same response. No iText license key, no OpenPDF CSS surprises, no bundled Chromium to upgrade every quarter.

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

## Quick start

Java 11+ `HttpClient`, no dependencies beyond the JDK. The connection is held until the file is ready; add `?wait=false` for an async ticket.

```
import java.net.URI;
import java.net.http.*;
import java.nio.file.*;

public class Capture {
  public static void main(String[] args) throws Exception {
    String key = System.getenv("WC_KEY");
    HttpClient client = HttpClient.newHttpClient();
    HttpRequest post = HttpRequest.newBuilder()
        .uri(URI.create("https://webcapture.io/v1/convert"))
        .header("Authorization", "Bearer " + key)
        .header("Content-Type", "application/json")
        .POST(HttpRequest.BodyPublishers.ofString(
            "{\"url\": \"https://example.com/report\"}"))
        .build();
    HttpResponse<String> res = client.send(post, HttpResponse.BodyHandlers.ofString());
    String download = /* parse "download" from the JSON receipt */ null;
    HttpRequest get = HttpRequest.newBuilder()
        .uri(URI.create(download))
        .header("Authorization", "Bearer " + key)
        .build();
    Files.write(Path.of("report.pdf"), client.send(get, HttpResponse.BodyHandlers.ofByteArray()).body());
  }
}
```

The receipt's `download` field keeps a legacy `.pdf` suffix for every format; use it as-is. The same endpoint covers [JavaScript](https://webcapture.io/html-to-pdf-api-javascript) and [PHP](https://webcapture.io/html-to-pdf-api-php).

## Why not the library

The JVM HTML-to-PDF field is a trade: iText renders well but its HTML module is commercial and its AGPL terms need a lawyer; OpenPDF and flying saucer predate a decade of CSS; driving Puppeteer from the JVM still means owning a Chromium binary and its upgrades. Here the renderer is ours and the API is one POST, so the Java side is an HTTP call with no native dependencies.

## The receipt and the ticket

Receipt, then ticket. The 200 body is one JSON object, and the fields a Java job acts on: `id` (every later call takes the id from this response), `bytes` (the finished document's size), `attempts` (the render passes used; 1 on a clean run), `remaining` (what is left of the monthly quota), `sourceUrl` and `sourceType` (the admitted source), and `download` (the key-scoped GET that carries the file). When a Java caller should not hold that connection open, a scheduled job with a tight window or a thread pool you do not want parked on I/O, add `?wait=false` and the endpoint answers `202` with a ticket instead: `{id, status: "queued", poll, download}`.

Poll the ticket's `poll` URL with the same Authorization header, never faster than about once a second. The status runs `queued`, then `rendering`, then `ready`; a failed status ends 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 finished artifacts stay downloadable for at least seven days (30 on Scale), so a nightly job can queue at 02:00 and collect on its own schedule. A key with a `webhookUrl` can receive a signed completion event instead (a Pro and Scale feature), but the poll endpoint stays the source of truth: webhook delivery is best-effort and can arrive twice.

```
// ticket is the 202 body: {"id": "cnv_...", "status": "queued",
//                          "poll": ".../v1/conversions/cnv_...",
//                          "download": ".../v1/conversions/cnv_....pdf"}
String status = "queued";
String body = "";
while (status.equals("queued") || status.equals("rendering")) {
  Thread.sleep(1000); // no faster than ~1 poll a second
  HttpRequest poll = HttpRequest.newBuilder(URI.create(ticketPoll))
      .header("Authorization", "Bearer " + key)
      .build();
  body = client.send(poll, HttpResponse.BodyHandlers.ofString()).body();
  status = jsonField(body, "status"); // your JSON parser, or the helper below
}
if (status.equals("failed")) throw new IllegalStateException(jsonField(body, "error"));

// Smallest honest parser for the one flat JSON object: a method on the same class.
private static String jsonField(String json, String field) {
  var m = Pattern.compile("\"" + field + "\"\s*:\s*"([^"]*)\"").matcher(json);
  return m.find() ? m.group(1) : null;
}
```

## Reading the failures

A refused call answers a JSON body with an `error` message, so the failure reaches your logs as a sentence instead of a bare status code. `401` says the Authorization header is missing, wrong, or the key was revoked; look at the header first, then the dashboard for revocations. `404` on a poll or download means the id belongs to a different key's account; remember the download path appends `.pdf` and the poll path does not, and copy both as given. `422` means the request itself was refused: 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 will not take, such as `pageSize` on a `format` that is not pdf.

`429` comes in three kinds the body distinguishes. The monthly quota wall carries `used`, `limit`, `resetDate`, and an `upgradeUrl`: nothing bills past quota, so the correct response is to wait for the month to turn over or follow the upgrade link. A full render queue or a rate-limited address carries `retryAfterSec` (the queue-full kind also sets a matching `retry-after` header): sleep that many seconds before resending the same request unchanged. And the in-flight cap (1, 3, or 10 concurrent renders by tier) carries `code`, `feature`, `requiredTier`, and `upgradeUrl` with neither a reset date nor a wait count: the documented next step is to wait for an in-flight render to finish, which in Java terms means pacing your submit loop. `502` is the page refusing 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.

```
HttpResponse<String> res = client.send(post, HttpResponse.BodyHandlers.ofString());
if (res.statusCode() == 429) {
  String body = res.body();
  if (body.contains("resetDate")) {
    // quota wall: used, limit, resetDate, upgradeUrl; nothing billed
    System.out.println("quota " + jsonField(body, "used") + "/" + jsonField(body, "limit")
        + " used, resets " + jsonField(body, "resetDate"));
  } else if (body.contains("retryAfterSec")) {
    Thread.sleep(Long.parseLong(jsonField(body, "retryAfterSec")) * 1000); // queue-full: resend unchanged
  } else {
    // concurrency cap: code, feature, requiredTier, upgradeUrl; wait for an in-flight render
  }
} else if (res.statusCode() >= 400) {
  throw new IOException(res.statusCode() + ": " + jsonField(res.body(), "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`, and full-page by default. Honest limits live on the [main API page](https://webcapture.io/html-to-pdf-api). The knobs a Java PDF job reaches for, straight from the reference's types and defaults:

| 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. |
| `blockAds` | boolean | false | Filter ad and tracker requests and hide leftover slots; best effort. |

The rest of the body (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.

## Printing pages behind a login

The quick start renders a page anyone can reach. The second job Java services get handed is a page behind a session: a portal statement, an internal report, anything that answers 401 to an anonymous GET. The renderer never logs in for you, but it carries the credentials you send: `fetch.httpHeaders` puts named headers on the source fetch, `fetch.auth` answers a basic-auth challenge, and `fetch.cookies` seeds the cookie jar. All three apply at the browser-context level, so the same credentials ride the page's subresource requests and its redirect hops, and every redirect hop re-runs the same public-target admission as the first.

```
String body = "{"
    + "\"url\": \"https://portal.example.com/statements/2026-11\","
    + "\"fetch\": {"
    +   "\"httpHeaders\": {\"Authorization\": \"Bearer sso-token-3f9c\"},"
    +   "\"cookies\": [{\"name\": \"session\", \"value\": \"3f9c...a1\"}]"
    + "}"
    + "}";

HttpRequest post = HttpRequest.newBuilder()
    .uri(URI.create("https://webcapture.io/v1/convert"))
    .header("Authorization", "Bearer " + key)
    .header("Content-Type", "application/json")
    .POST(HttpRequest.BodyPublishers.ofString(body))
    .build();
```

The reference's own limits, worth knowing before the first run: at most 20 headers, names up to 128 characters of RFC token characters, values up to 1024 characters of printable ASCII. A `cookie` header is refused in `httpHeaders`: pass cookies through `fetch.cookies`, an array of `{name, value}` entries, also at most 20, and pinned to the rendered URL's host rather than any caller-named domain. The cookie jar lives for exactly one render: every render opens a fresh browser context, so nothing carries over to the next call. For endpoints that speak plain basic auth instead of tokens, `fetch.auth` takes `{username, password}` (up to 255 characters each) and answers the 401 challenge on every request of the render. Keep all of it server-side: these fields carry session credentials, so they have exactly the same trust class as the key itself.

## When to pick the Java route

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

| If your world looks like | Pick | Why |
| --- | --- | --- |
| A JVM batch job already owns the schedule | Java | One `HttpClient` call in the job you already run: no new runtime to deploy, no second process to supervise, and the 202 ticket fits a job's thread budget. |
| Spring (or Micronaut, Quarkus) owns the web tier | Java | A thin service wrapper around the endpoint: your code owns auth, auditing, and retries; the render, the Chromium upgrades, and the print CSS stay out of the container. |
| The team lives in Node and deploys serverless | [JavaScript](https://webcapture.io/html-to-pdf-api-javascript) | The same endpoint with a `fetch` body; the JavaScript page shows the batch-queue-and-poll loop that shape runs. |
| The stack is PHP: cron, WordPress, Laravel | [PHP](https://webcapture.io/html-to-pdf-api-php) | The same endpoint over cURL, which every PHP deployment already has; the PHP page shows the scheduled-report pattern. |

The receipt and the error envelope read the same in any of the three languages, so a pipeline can start where the team already is and move later without re-reading the API.

The price ladder: Free covers 50 renders a month, Pro $19 for 5,000, Scale $69 for 35,000. Full terms on the [pricing page](https://webcapture.io/pricing); further 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.