# Documents (/docs/concepts/documents)

> What a document is, how it moves from request to file, and how to render, wait for, list, download and keep track of documents.

A document is one render request and its result. Each call to [`POST /v1/documents`](/docs/api-reference/documents/create) that Druckling accepts creates one, whether it renders right away, is queued for later, or fails validation. The document records what you asked for (template, version, format, language) and, once it renders, points at the file: a PDF, a PNG or an e-invoice XML.

You poll documents, list them, download their files, [share them](/docs/concepts/share-links) and receive [webhooks](/docs/guides/webhooks) about them. Document IDs start with `pdf_`, whatever the format.

## Lifecycle [#lifecycle]

A document moves through these statuses:

| Status | What it means |
| --- | --- |
| `queued` | Accepted with `async: true` and waiting for a render worker. |
| `rendering` | The file is being rendered. A synchronous request returns only after this. |
| `rendered` | The file is stored and `url` holds a signed download link. |
| `failed` | Validation or rendering failed. `error` says why. This status is final. |
| `expired` | The file was deleted at the end of the retention period. The record stays. |

`rendered` and `failed` are the outcomes of a render; `expired` follows `rendered` once [retention](#retention) ends.

A few things to know about the transitions:

- **Validation comes first.** Druckling checks `data` against the template's [JSON Schema](/docs/concepts/variables) before rendering or queueing anything. A payload that doesn't match still creates a document, with status `failed`, and the request fails with `422`. The error body carries the new document's ID in `data.documentId`, so you can find the failed attempt later.
- **Some requests never create a document.** A malformed request (`400`), a missing or invalid key (`401`), a missing permission (`403`), an unknown template or version (`404`), a `format` or `image` option the template doesn't support (`422`) and an exhausted quota (`429`) are rejected before a document exists. See [Errors](/docs/concepts/errors).
- **Webhooks follow the status.** `document.rendered` fires when a document reaches `rendered`, `document.failed` when it reaches `failed` (validation failures included), and `document.expired` when its file is deleted.

## Output formats [#output-formats]

The `format` field decides what the document contains. When you leave it out, the template decides.

| `format` | `content_type` | When to use it |
| --- | --- | --- |
| `pdf` | `application/pdf` | The default for every template except XRechnung and Peppol BIS e-invoice templates. Factur-X / ZUGFeRD templates produce a PDF/A-3 with the invoice XML embedded. |
| `png` | `image/png` | One page as an image, for previews and thumbnails. Pick the page with `image.page` (default 1) and the resolution with `image.scale` (pixels per point, 0.5 to 4, default 2 = 144 dpi). |
| `xml` | `application/xml` | XRechnung and Peppol BIS e-invoice templates, which produce only XML. |

The template has to support the format you ask for, otherwise the request fails with `422 validation_failed` on `format`:

- Factur-X templates render to `pdf` only.
- XRechnung and Peppol BIS templates render to `xml` only, and `xml` needs one of those templates.
- `image` options are only allowed with `format: "png"` (`422` on `image`).
- A template's PDF/A or PDF/UA setting applies to PDFs only. A PNG of such a template renders normally and notes this on its timeline.

See [PNG output](/docs/guides/png-output) and [E-invoicing](/docs/guides/e-invoicing) for the details of each.

## Synchronous rendering [#synchronous-rendering]

By default the request waits for the render and returns the finished document with `200 OK`:

```bash tab="cURL"
curl https://druckling-nine.vercel.app/v1/documents \
  -H "Authorization: Bearer $DRUCKLING_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "template": "invoice-standard",
    "filename": "INV-2041",
    "data": {
      "invoice": { "number": "INV-2041", "due_date": "2026-11-22" },
      "customer": { "name": "Northwind Ltd.", "address": "12 Pier St, Leeds" },
      "line_items": [
        { "description": "Design system audit", "qty": 12, "rate": 180, "amount": 2160 }
      ],
      "totals": { "subtotal": 2160, "tax": 172.8, "amount": 2332.8 }
    }
  }'
```

```ts tab="TypeScript"
import Druckling from "@druckling/sdk";

const druckling = new Druckling();

const document = await druckling.documents.create({
  template: "invoice-standard",
  filename: "INV-2041",
  data: {
    invoice: { number: "INV-2041", due_date: "2026-11-22" },
    customer: { name: "Northwind Ltd.", address: "12 Pier St, Leeds" },
    line_items: [{ description: "Design system audit", qty: 12, rate: 180, amount: 2160 }],
    totals: { subtotal: 2160, tax: 172.8, amount: 2332.8 },
  },
});
```

```python tab="Python"
from druckling import Druckling

client = Druckling()

document = client.documents.create(
    template="invoice-standard",
    filename="INV-2041",
    data={
        "invoice": {"number": "INV-2041", "due_date": "2026-11-22"},
        "customer": {"name": "Northwind Ltd.", "address": "12 Pier St, Leeds"},
        "line_items": [{"description": "Design system audit", "qty": 12, "rate": 180, "amount": 2160}],
        "totals": {"subtotal": 2160, "tax": 172.8, "amount": 2332.8},
    },
)
```

```php tab="PHP"
$druckling = new Druckling\Druckling();

$document = $druckling->documents->create(
    template: 'invoice-standard',
    filename: 'INV-2041',
    data: [
        'invoice' => ['number' => 'INV-2041', 'due_date' => '2026-11-22'],
        'customer' => ['name' => 'Northwind Ltd.', 'address' => '12 Pier St, Leeds'],
        'line_items' => [['description' => 'Design system audit', 'qty' => 12, 'rate' => 180, 'amount' => 2160]],
        'totals' => ['subtotal' => 2160, 'tax' => 172.8, 'amount' => 2332.8],
    ],
);
```

```json title="Response"
{
  "id": "pdf_8Qw2kLm3nP0aB1cD",
  "object": "document",
  "status": "rendered",
  "template": "invoice-standard",
  "version": 1,
  "filename": "INV-2041.pdf",
  "format": "pdf",
  "content_type": "application/pdf",
  "image": null,
  "pages": 1,
  "size_bytes": 48213,
  "url": "https://…",
  "expires_at": "2026-11-26T09:14:03.120Z",
  "error": null,
  "einvoice": null,
  "batch": null,
  "language": "en",
  "test_mode": true,
  "created_at": "2026-10-27T09:14:02.384Z"
}
```

### Time limits [#time-limits]

Typesetting a document is limited to **10 seconds**. A render that takes longer is stopped: the request fails with `504` and code `render_timeout`, and the document ends up `failed` with the same code.

The whole request can take longer than the typesetting step, since Druckling also fetches images, may wait for a free render worker, and stores the file. Give your HTTP client a timeout of about 60 seconds, which is what the SDKs use by default.

If the template can't be rendered (a Typst error, or more pages than the [page limit](#pages-and-size)), the request fails with `422 render_failed` and the document is `failed`.

## Asynchronous rendering [#asynchronous-rendering]

Set `async: true` to queue the render and get an answer right away. Druckling validates `data` first, so schema errors still come back on this request as a `422`. A valid request returns `202 Accepted` with status `queued`, `url: null`, and the document ID you use to follow it:

```bash
curl https://druckling-nine.vercel.app/v1/documents \
  -H "Authorization: Bearer $DRUCKLING_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "template": "invoice-standard",
    "async": true,
    "data": {
      "invoice": { "number": "INV-2042", "due_date": "2026-11-29" },
      "customer": { "name": "Northwind Ltd.", "address": "12 Pier St, Leeds" },
      "line_items": [
        { "description": "Workshop facilitation", "qty": 2, "rate": 640, "amount": 1280 }
      ],
      "totals": { "subtotal": 1280, "tax": 102.4, "amount": 1382.4 }
    }
  }'
```

```json title="Response"
{
  "id": "pdf_3Rt8vXq1mK6sJ2nB",
  "object": "document",
  "status": "queued",
  "template": "invoice-standard",
  "version": 1,
  "filename": "invoice-standard-3Rt8vXq1.pdf",
  "format": "pdf",
  "content_type": "application/pdf",
  "image": null,
  "pages": null,
  "size_bytes": null,
  "url": null,
  "expires_at": null,
  "error": null,
  "einvoice": null,
  "batch": null,
  "language": "en",
  "test_mode": true,
  "created_at": "2026-10-27T09:20:11.042Z"
}
```

Choose asynchronous rendering when the caller shouldn't wait, for example inside a web request handler, or when you already process [webhooks](/docs/guides/webhooks). It doesn't buy a render more time: the same 10-second typesetting limit applies. To render many documents at once, use a [batch](/docs/guides/batches) instead of many separate requests.

A queued render that fails, for example with a Typst error or a timeout, is final: Druckling doesn't render that document again. Payload [size limits](/docs/concepts/plans-and-limits#payload-and-render-limits) are checked when the document renders, so an oversized asynchronous payload shows up as a `failed` document with `error.code: "payload_too_large"`, not as an error on the request.

## Wait for a document [#wait-for-a-document]

### Use webhooks [#use-webhooks]

A [webhook endpoint](/docs/guides/webhooks) subscribed to `document.rendered` and `document.failed` tells you the moment a document is done. The event's `data` is the full document, including a freshly signed `url`. This is the recommended way to follow asynchronous renders: it costs no API requests and has no polling delay.

### Poll [#poll]

Without webhooks, retrieve the document with [`GET /v1/documents/{id}`](/docs/api-reference/documents/get) until its status is `rendered`, `failed` or `expired`. Each poll is an API request and counts toward your key's [rate limit](/docs/concepts/plans-and-limits#rate-limits), so poll every couple of seconds rather than in a tight loop, and stop after a deadline.

```bash tab="cURL"
id="pdf_3Rt8vXq1mK6sJ2nB"

for attempt in $(seq 1 30); do
  doc=$(curl -s "https://druckling-nine.vercel.app/v1/documents/$id" \
    -H "Authorization: Bearer $DRUCKLING_API_KEY")
  status=$(echo "$doc" | jq -r .status)
  case "$status" in
    rendered) echo "$doc" | jq -r .url; break ;;
    failed|expired) echo "$doc" | jq .error; exit 1 ;;
  esac
  sleep 2
done
```

```ts tab="TypeScript"
const queued = await druckling.documents.create({ template: "invoice-standard", data, async: true });

const document = await druckling.documents.wait(queued, { intervalMs: 2_000, timeoutMs: 60_000 });
console.log(document.url);
```

```python tab="Python"
queued = client.documents.create(template="invoice-standard", data=data, async_=True)

document = client.documents.wait(queued, interval=2, timeout=60)
print(document.url)
```

```php tab="PHP"
$queued = $druckling->documents->create(template: 'invoice-standard', data: $data, async: true);

$document = $druckling->documents->wait($queued, timeout: 60, interval: 2);
echo $document->url;
```

The SDK wait helpers return the document once it's `rendered`. They throw a document-failed error when it ends up `failed` or `expired`, and a wait-timeout error when the deadline passes first. Their default is a poll every second for up to 120 seconds.

## List documents [#list-documents]

[`GET /v1/documents`](/docs/api-reference/documents/list) returns the documents of your API key's mode, newest first. A test key lists test documents and a live key lists live ones.

| Parameter | Description |
| --- | --- |
| `limit` | Documents per page, 1 to 100. Default 25. |
| `cursor` | The `next_cursor` of the previous page. Treat it as opaque. |
| `status` | Only documents with this status, e.g. `failed`. |
| `template` | Only documents rendered from this template slug. |

The response has `object: "list"`, the page in `data`, and `next_cursor`, which is `null` on the last page:

```bash
curl "https://druckling-nine.vercel.app/v1/documents?status=failed&template=invoice-standard&limit=50" \
  -H "Authorization: Bearer $DRUCKLING_API_KEY"
```

To get the next page, repeat the request with `cursor` set to `next_cursor`. The SDKs do this for you when you iterate:

```ts tab="TypeScript"
for await (const doc of druckling.documents.list({ status: "failed" })) {
  console.log(doc.id, doc.filename);
}
```

```python tab="Python"
for doc in client.documents.list(status="failed"):
    print(doc.id, doc.filename)
```

```php tab="PHP"
foreach ($druckling->documents->list(status: 'failed') as $doc) {
    echo $doc->id, ' ', $doc->filename, PHP_EOL;
}
```

<Callout type="warn" title="List results leave out url, expires_at and error">

Documents in a list always have `url`, `expires_at` and `error` set to `null`, even when the document has a file or an error. Retrieve a document by ID to get its download link, its expiry and the reason it failed.

</Callout>

## File names [#file-names]

`filename` sets the file's name, up to 200 characters. Druckling cleans it up:

- Slashes, backslashes and control characters are removed, and surrounding whitespace is trimmed.
- The extension always matches the format. Druckling adds `.pdf`, `.png` or `.xml`, and replaces one of those that doesn't match: `INV-2041` becomes `INV-2041.pdf`, and `INV-2041.png` rendered as a PDF becomes `INV-2041.pdf`.
- Without a `filename`, the name is the template slug plus part of the document ID, e.g. `invoice-standard-8Qw2kLm3.pdf`.

Names don't have to be unique. [Share links](/docs/concepts/share-links) serve the file under this name, and the dashboard shows it. The signed `url` doesn't use it: the link's path ends in the document ID, so name the file yourself when you save a download.

## Pages and size [#pages-and-size]

`pages` is the page count of a PDF, `1` for a PNG and `null` for XML. `size_bytes` is the size of the stored file. Both are `null` until the document is rendered.

A document can have as many pages as your plan allows: 50 on Free, 100 on Starter, 200 on Pro and 500 on Business. A longer one fails with `422 render_failed` ("The document has 64 pages; your plan allows 50 per document"); the error's `data.pages` holds the count and `data.limit` the limit. The limit applies to the laid-out document, so it also applies when you render a single page as a PNG. See [Plans and limits](/docs/concepts/plans-and-limits#payload-and-render-limits) for the other limits.

## Download the file [#download-the-file]

A rendered document's `url` is a signed link to the file in Druckling's private storage. Whoever has the link can download the file without an API key, so treat it like a password: keep it out of logs and public pages, and don't send your API key along to it.

```bash tab="cURL"
url=$(curl -s "https://druckling-nine.vercel.app/v1/documents/pdf_8Qw2kLm3nP0aB1cD" \
  -H "Authorization: Bearer $DRUCKLING_API_KEY" | jq -r .url)

curl -o INV-2041.pdf "$url"
```

```ts tab="TypeScript"
import { writeFile } from "node:fs/promises";

const bytes = await druckling.documents.download("pdf_8Qw2kLm3nP0aB1cD");
await writeFile("INV-2041.pdf", bytes);
```

```python tab="Python"
client.documents.download_to("pdf_8Qw2kLm3nP0aB1cD", "INV-2041.pdf")
```

```php tab="PHP"
$druckling->documents->downloadTo('pdf_8Qw2kLm3nP0aB1cD', 'INV-2041.pdf');
```

How the link behaves:

- **It's short-lived.** A link works for up to 7 days after the API returned it, and never after the document's `expires_at`. The API doesn't report a link's own expiry, so don't store links for later.
- **Every read signs a new one.** Retrieving the document returns a fresh link, and so does each `document.rendered` webhook. When you need the file later, retrieve the document again. The SDK download helpers do this when you pass an ID.
- **It's `null` when there's nothing to download**: while the document is `queued` or `rendering`, when it `failed` or `expired`, once `expires_at` has passed, and in [list results](#list-documents).

To give the file to someone who doesn't use your API, create a [share link](/docs/concepts/share-links) instead.

## Retention [#retention]

Druckling keeps rendered files for a limited time on every plan:

| What | How long |
| --- | --- |
| Rendered file | 30 days after rendering. `expires_at` says when it's deleted. |
| Signed download link | Up to 7 days after it was returned, and never past `expires_at`. |
| Request body shown in the dashboard | 30 days, then removed. Bodies larger than 64 KB aren't stored. |
| Document record (status, file name, pages, timeline) | 1 year. After that, retrieving the document returns `404`. |

A daily cleanup job deletes files whose `expires_at` has passed, sets their documents to `expired`, and sends `document.expired`. Until the job has run, such a document still reads `rendered`, but its `url` is already `null`. Share links to the document stop working at `expires_at` too.

Retention is the same on every plan. If you need files for longer, download them when they're rendered (for example from your `document.rendered` webhook handler) and store them yourself.

## Failed documents [#failed-documents]

A `failed` document has an `error` object:

```json
{
  "id": "pdf_6Jd2pRw9tL4xQ8sM",
  "object": "document",
  "status": "failed",
  "template": "invoice-standard",
  "version": 1,
  "filename": "INV-2043.pdf",
  "format": "pdf",
  "content_type": "application/pdf",
  "image": null,
  "pages": null,
  "size_bytes": null,
  "url": null,
  "expires_at": null,
  "error": {
    "code": "schema_validation_failed",
    "message": "Required field customer.address was missing from the request payload",
    "field": "customer.address"
  },
  "einvoice": null,
  "batch": null,
  "language": "en",
  "test_mode": true,
  "created_at": "2026-10-27T09:31:45.906Z"
}
```

`field` is the dotted path of the offending value, with array indexes as numbers, e.g. `line_items.2.qty`. It's `null` when the error isn't about one field. The codes you'll see on documents:

| `error.code` | Why the document failed |
| --- | --- |
| `schema_validation_failed` | `data` doesn't match the template's JSON Schema. |
| `validation_failed` | A rule the schema can't express, such as an e-invoice business rule (`BR-CO-25` and so on), or a PNG `image.page` past the end of the document. |
| `render_failed` | The template couldn't be rendered, or the document had more pages than your plan allows. |
| `render_timeout` | Typesetting took longer than 10 seconds. |
| `payload_too_large` | `data` exceeded a [payload limit](/docs/concepts/plans-and-limits#payload-and-render-limits). |
| `canceled` | The document was an item of a [batch](/docs/guides/batches) that was canceled before it rendered. |

Rarely, you may also see `rate_limited` (the render engine was overloaded), or `not_found` (the template version disappeared before a queued render started). The API has no retry endpoint: fix the payload or the template and send a new request. See [Errors](/docs/concepts/errors) for every code and what to do about it.

## In the dashboard [#in-the-dashboard]

**Documents** lists the documents of the mode you're in; switch with **Test mode** in the sidebar. Filter by period, status, template and API key, search by file name or document ID, and export the list as CSV. The **Retention** button shows how long files and links are kept.

Click a document to open its details:

- Its status, format, mode, template version and creation time.
- For a failed document, the error and the offending field, plus **Retry with test data**, which renders the template again with its sample data as a new document in the same mode.
- For a rendered document, the page count, file size and render time, a download button, and its [share links](/docs/concepts/share-links).
- The **Timeline**: when the request was received, validated, queued, rendered, stored or failed, retries, notes (for example that a PDF standard doesn't apply to a PNG), and expiry.
- The **Request body** as Druckling received it, until it's removed after 30 days.
- The API key that created it, the language, the batch it belongs to and the engine versions.

## Next steps [#next-steps]

<Cards>
  <Card title="Share links" href="/docs/concepts/share-links">
    Give people a link to a rendered document without an API key.
  </Card>
  <Card title="Webhooks" href="/docs/guides/webhooks">
    Get notified when documents render, fail or expire.
  </Card>
  <Card title="PNG output" href="/docs/guides/png-output">
    Render one page as an image for previews and thumbnails.
  </Card>
  <Card title="E-invoicing" href="/docs/guides/e-invoicing">
    Produce Factur-X, ZUGFeRD, XRechnung and Peppol BIS invoices.
  </Card>
</Cards>
