# Authentication (/docs/authentication)
> Authenticate API requests with a secret API key, choose its mode and permission, and rotate or revoke it safely.
Every request to the Druckling API is authenticated with a secret API key. A key belongs to one workspace and decides three things: which workspace the request acts in, whether it runs in live or test mode, and what it's allowed to do.
## Send your API key [#send-your-api-key]
Send the key in the `Authorization` header with the `Bearer` scheme:
```bash tab="Authorization"
curl https://druckling-nine.vercel.app/v1/documents \
-H "Authorization: Bearer $DRUCKLING_API_KEY"
```
```bash tab="x-api-key"
curl https://druckling-nine.vercel.app/v1/documents \
-H "x-api-key: $DRUCKLING_API_KEY"
```
Both headers work the same way. If a request has both, the `Authorization: Bearer` header is used. The SDKs send `Authorization: Bearer` and read the key from the `DRUCKLING_API_KEY` environment variable unless you pass one explicitly. See [SDKs](/docs/sdks).
The same keys authenticate the hosted [MCP server](/docs/guides/mcp), with the same permissions.
## Key format [#key-format]
A key is a mode prefix followed by 64 random letters:
| Prefix | Mode |
| --- | --- |
| `dr_live_` | Live: production renders that count toward your plan's quota |
| `dr_test_` | Test: free renders, kept apart from live data |
The prefix is the only thing that decides the mode: there's no header or parameter to switch it. See [Test mode](/docs/concepts/test-mode) for what's separated between the two.
Druckling stores a hash of the key, not the key itself, so the full key is shown only once, when you create it. The dashboard identifies keys by their name and their first characters, for example `dr_live_xKpQ••••`. Keys don't expire; they work until you revoke them.
## Permissions [#permissions]
Each key has one of two permission levels. Pick **Render only** for services that only render documents, and **Full access** only where you need templates, webhooks or the embedded editor.
| | Render only | Full access |
| --- | --- | --- |
| Scopes | `documents:create`, `documents:read` | `documents:create`, `documents:read`, `templates:read`, `templates:write`, `webhooks:manage` |
| [Documents](/docs/api-reference/documents/create): render, retrieve, list | Yes | Yes |
| [Batches](/docs/api-reference/batches/create): start, retrieve, list, list documents, cancel | Yes | Yes |
| [Share links](/docs/api-reference/share-links/create): create, list, revoke | Yes | Yes |
| [Templates](/docs/api-reference/templates/list): list, retrieve with JSON Schema | No | Yes |
| [Webhook endpoints](/docs/api-reference/webhooks/create): create, list, retrieve, delete | No | Yes |
| [Embedded editor sessions](/docs/api-reference/embedded-editor/create): create, revoke | No | Yes |
| MCP server: render and read documents | Yes | Yes |
| MCP server: list, read, create, edit and publish templates | No | Yes |
A render-only key can render any published template, as long as you know its slug. It just can't list templates or read their schemas.
## Keys and workspaces [#keys-and-workspaces]
A key works in the workspace it was created in. Everything it creates, such as documents, batches and webhook endpoints, belongs to that workspace, and it can't reach any other. If you belong to several workspaces, create a key in each.
A key isn't tied to the person who created it. It keeps working when that person leaves the workspace.
## Manage keys [#manage-keys]
Keys are managed in the dashboard under **Developers › API keys**. Owners and admins can create and revoke keys. Members can see the list, with each key's name, mode, permission, when it was last used and when it was created, but can't change it.
Keys can't be renamed or edited. To change a key's mode or permission, create a new key and revoke the old one.
### Create a key [#create-a-key]
1. Go to **Developers › API keys** and click **Create API key**.
2. Name the key after the service that uses it, for example `billing-service`. Keep the name to 32 characters or fewer.
3. Choose the mode, **Test** or **Live**, and the permission, **Render only** or **Full access**.
4. Click **Create key**, copy the key and store it in your server's environment or secret manager. You won't be able to see it again.
### Rotate a key [#rotate-a-key]
There's no in-place rotation. Both keys work at the same time, so rotate without downtime:
1. Create a new key with the same mode and permission.
2. Deploy it everywhere the old key is used.
3. Check that the old key's **Last used** time no longer changes.
4. Revoke the old key.
### Revoke a key [#revoke-a-key]
Open the key's actions menu in the list, choose **Revoke key** and confirm. Requests that use it fail with `401` right away. Revoking can't be undone.
## Keep keys secret [#keep-keys-secret]
API keys are server-side secrets:
- Keep them in environment variables or a secret manager, never in source control.
- Never ship a key to a browser or a mobile app. Anyone who has it can act in your workspace: render documents (on your quota, with a live key) and, with full access, read your templates and manage your webhooks and editor sessions.
- To let your users edit templates in your product, create a short-lived [embedded editor session](/docs/guides/embedded-editor) on your server and give its URL to the browser. A session can only work on one template and expires after at most an hour.
- To give someone a rendered document, send them a [share link](/docs/concepts/share-links) or the document's signed `url`. Neither needs a key.
If a key leaks, revoke it, create a replacement, and look through **Developers › Logs** for requests you don't recognize. The Logs page shows the dashboard's current mode, so switch to test mode to see a test key's requests.
## Authentication errors [#authentication-errors]
Authentication errors have the same shape as every other [error](/docs/concepts/errors):
```json
{
"defined": false,
"code": "UNAUTHORIZED",
"status": 401,
"message": "Invalid or revoked API key",
"data": { "code": "unauthorized", "field": null }
}
```
| Status | `data.code` | Message | Cause |
| --- | --- | --- | --- |
| 401 | `unauthorized` | Missing API key. Send it as `x-api-key` or `Authorization: Bearer`. | No key in the request. |
| 401 | `unauthorized` | Invalid or revoked API key | The key is mistyped, incomplete or revoked. |
| 403 | `forbidden` | This API key does not have the templates:read permission | A render-only key called `GET /v1/templates` or `GET /v1/templates/{slug}`. |
| 403 | `forbidden` | This API key does not have the webhooks:manage permission | A render-only key listed or retrieved webhook endpoints. |
| 403 | `forbidden` | Only owners and admins can manage webhooks | A render-only key created or deleted a webhook endpoint. |
| 403 | `forbidden` | Creating editor sessions needs a full-access API key (templates:write) | A render-only key created or revoked an embedded editor session. |
| 429 | `rate_limited` | Too many requests for this API key | The key sent too many requests in a short time. See [Plans and limits](/docs/concepts/plans-and-limits). |
Requests that fail with the `401` and `429` errors above aren't recorded under **Developers › Logs**. Requests rejected with `403` are.
# 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;
}
```
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.
## 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]
Give people a link to a rendered document without an API key.
Get notified when documents render, fail or expire.
Render one page as an image for previews and thumbnails.
Produce Factur-X, ZUGFeRD, XRechnung and Peppol BIS invoices.
# Errors (/docs/concepts/errors)
> The shape of Druckling API errors, every error code and its HTTP status, and how to retry without rendering a document twice.
Druckling answers every request with a conventional HTTP status code: `2xx` when it worked, `4xx` when something about the request needs to change, and `5xx` when something went wrong on Druckling's side. Errors come with a JSON body that tells you what happened and, for most errors, which field caused it.
## Error format [#error-format]
```json title="422 Unprocessable Content"
{
"defined": false,
"code": "UNPROCESSABLE_CONTENT",
"status": 422,
"message": "Required field customer.address was missing from the request payload",
"data": {
"code": "schema_validation_failed",
"field": "customer.address",
"documentId": "pdf_6Jd2pRw9tL4xQ8sM",
"errors": [
{ "field": "customer.address", "message": "missing required field customer.address" },
{ "field": "invoice.due_date", "message": "invoice.due_date must be a date like 2026-11-22" }
]
}
}
```
Depending on the error, `data` holds more fields, such as `documentId`, `errors`, `retryAfter` or `diagnostics`. They're described with each code below.
A few responses don't have `data.code`: request validation errors (`400`), unexpected server errors (`500`) and requests to an unknown endpoint (`404`). Fall back to the top-level `code` for those, which is what the SDKs do.
## Request validation errors [#request-validation-errors]
Before a request reaches Druckling's own checks, its shape is validated against the API's schema: required fields, types, allowed values and ranges. A request that doesn't match fails with `400 BAD_REQUEST`, and `data.issues` lists every problem:
```bash
curl https://druckling-nine.vercel.app/v1/documents \
-H "Authorization: Bearer $DRUCKLING_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "data": { "invoice": { "number": "INV-2041" } }, "async": "yes" }'
```
```json title="400 Bad Request"
{
"defined": false,
"code": "BAD_REQUEST",
"status": 400,
"message": "Input validation failed",
"data": {
"issues": [
{
"expected": "string",
"code": "invalid_type",
"path": ["template"],
"message": "Invalid input: expected string, received undefined"
},
{
"expected": "boolean",
"code": "invalid_type",
"path": ["async"],
"message": "Invalid input: expected boolean, received string"
}
]
}
}
```
Each issue's `path` is an array of keys and array indexes. A body that isn't valid JSON gets `400` with the message "Malformed request…" and no `data`. Fields the API doesn't know are ignored, not rejected.
The API key is checked first, so a request with a missing or invalid key gets `401` even if its body is also invalid.
## Error codes [#error-codes]
| `data.code` | Status | `code` | When it happens |
| --- | --- | --- | --- |
| `unauthorized` | `401` | `UNAUTHORIZED` | The API key is missing ("Missing API key…"), or it's invalid or revoked ("Invalid or revoked API key"). |
| `forbidden` | `403` | `FORBIDDEN` | The key lacks a permission, for example a Render only key reading templates, managing webhooks or creating editor sessions. |
| `not_found` | `404` | `NOT_FOUND` | No such document, batch, share link, webhook endpoint or template. Also a template without a published version (`field: "template"`) and an unknown `version` (`field: "version"`). |
| `conflict` | `409` | `CONFLICT` | A count limit is reached: 20 active share links per document, or 20 webhook endpoints per workspace. |
| `invalid_state` | `409` | `CONFLICT` | The object can't do that right now: sharing a document that isn't `rendered`, canceling a batch that already finished, or creating an editor session before any origin is allowed in **Settings › Embed**. |
| `stale_revision` | `409` | `CONFLICT` | Only in the dashboard and editors: someone else saved the template first. The REST API doesn't return it. |
| `schema_validation_failed` | `422` | `UNPROCESSABLE_CONTENT` | `data` doesn't match the template's JSON Schema: a required field is missing, or a value has the wrong type or format. |
| `validation_failed` | `422` | `UNPROCESSABLE_CONTENT` | The request is well-formed but breaks a rule the schema can't express: a `format` or `image` option the template doesn't support, a PNG `image.page` past the end of the document, a `language` the template doesn't have, an e-invoice business rule, or `data` nested deeper than 32 levels. |
| `payload_too_large` | `413` | `PAYLOAD_TOO_LARGE` | `data` is larger than 1,000,000 bytes, an array in it has more than 10,000 items, or a batch's `items` exceed 4 MB. |
| `quota_exceeded` | `429` | `QUOTA_EXCEEDED` | Your plan's daily or monthly live document quota is used up. |
| `rate_limited` | `429` | `TOO_MANY_REQUESTS` | The API key made too many requests, too many editor sessions were created at once, or the render engine is busy. |
| `render_failed` | `422` | `UNPROCESSABLE_CONTENT` | The template couldn't be rendered: a Typst error, more pages than your plan allows, or an unexpected failure while rendering or storing the file. |
| `render_timeout` | `504` | `GATEWAY_TIMEOUT` | Typesetting took longer than 10 seconds and was stopped. |
And the responses without `data.code`:
| Status | `code` | When it happens |
| --- | --- | --- |
| `400` | `BAD_REQUEST` | The request doesn't match the API's schema, or the body isn't valid JSON. See [request validation errors](#request-validation-errors). |
| `404` | `NOT_FOUND` | The path doesn't exist. The body is just `{ "code": "NOT_FOUND", "message": "Unknown endpoint" }`. |
| `500` | `INTERNAL_SERVER_ERROR` | Something unexpected went wrong on Druckling's side. The message is "Internal server error". |
Limits behind these codes are listed in [Plans and limits](/docs/concepts/plans-and-limits).
## Validation errors [#validation-errors]
Druckling validates a render request in two steps, and the code tells you which one failed:
- **`schema_validation_failed`**: `data` doesn't match the template's [JSON Schema](/docs/concepts/variables). `data.field` is the first problem, with missing fields first, and `data.errors` lists every problem as `{ field, message }`.
- **`validation_failed`**: the payload has the right shape but breaks a rule, or the request asks for something the template can't do. For e-invoice templates, `data.errors` lists the broken business rules, each with a `rule` such as `BR-CO-25`, and the rule's ID also appears in the message. See [E-invoicing](/docs/guides/e-invoicing).
Field paths are dotted, and array indexes are numbers: `line_items.2.qty` is the `qty` of the third line item.
When `data` fails either check, Druckling still creates a document, in status `failed`, and `data.documentId` holds its ID. That's how the attempt shows up in **Documents** in the dashboard, and why it triggers a `document.failed` [webhook](/docs/guides/webhooks). It doesn't count toward your quota. Errors about the request itself, such as an unsupported `format` or an unknown `language`, are rejected before a document is created.
### Batch validation errors [#batch-validation-errors]
[`POST /v1/batches`](/docs/api-reference/batches/create) validates every item before rendering anything. If any item is invalid, nothing is rendered, no documents are created, and the answer is `422`. `data.field` points into the first invalid item, `data.invalidItems` counts the invalid items, and `data.errors` lists the first problem of each of the first 20 invalid items, with `field` relative to that item's `data`:
```json title="422 Unprocessable Content"
{
"defined": false,
"code": "UNPROCESSABLE_CONTENT",
"status": 422,
"message": "Item 3: Required field customer.address was missing from the request payload (2 of 50 items are invalid)",
"data": {
"code": "schema_validation_failed",
"field": "items.3.data.customer.address",
"invalidItems": 2,
"errors": [
{ "index": 3, "field": "customer.address", "message": "Required field customer.address was missing from the request payload" },
{ "index": 17, "field": "invoice.due_date", "message": "Required field invoice.due_date was missing from the request payload" }
]
}
}
```
See [Batches](/docs/guides/batches) for the whole flow.
## Render errors [#render-errors]
`render_failed` (`422`) means the template couldn't be turned into a file with this payload:
- **A Typst error.** `data.diagnostics` lists the engine's messages, each with a `severity`, a `message`, and the template block it came from when Druckling can tell. Open the template in the editor with the same data to see the problem.
- **Too many pages.** "The document has 64 pages; the limit is 50", with the count in `data.pages`.
- **An unexpected failure**, such as "Rendering failed unexpectedly". These can be temporary.
`render_timeout` (`504`) means typesetting took longer than 10 seconds and was stopped.
In both cases the document is recorded as `failed` with the same `error.code`, and it doesn't count toward your quota. With `async: true` you don't get these errors on the request: the document ends up `failed` instead, and `document.failed` tells you. See [Documents](/docs/concepts/documents#failed-documents).
## Retrying [#retrying]
Whether a retry can help depends on the error:
| Error | Retry? |
| --- | --- |
| `429 rate_limited` | Yes, after a pause. Wait for the `Retry-After` header (also in `data.retryAfter`). The per-key limit counts 120 requests a minute. See [rate limits](/docs/concepts/plans-and-limits#rate-limits). |
| `429 quota_exceeded` | No. Wait for the quota to reset, upgrade, or use a test key while developing. |
| `500` and other `5xx` | Yes for `GET` and `DELETE`, with exponential backoff. For `POST`, read [idempotency](#idempotency) first. |
| `504 render_timeout` | At most once. If it times out again, make the document lighter, for example with fewer table rows or images. |
| `422 render_failed` | Not until you fix the template or the payload, unless it's an unexpected failure without `data.diagnostics`. |
| `400`, `401`, `403`, `404`, `409`, `413`, other `422` | No. Fix the request first. |
| No response (network error, client timeout) | Yes for `GET` and `DELETE`. For `POST`, the server may have done the work: read [idempotency](#idempotency). |
Each `POST /v1/documents` that Druckling accepts creates a new document, and attempts that failed validation or rendering stay in your document list as `failed` documents.
## Idempotency [#idempotency]
The API doesn't support idempotency keys. An `Idempotency-Key` header is ignored, and every `POST /v1/documents` that passes validation renders a new document, which counts toward your quota in live mode.
Duplicates happen when a request reaches Druckling but the response never reaches you: the connection drops, or your client times out during a synchronous render. The document may have rendered anyway. To keep this from creating duplicates:
- **Name documents uniquely.** Set `filename` to something unique, such as the invoice number. After a network error or a `5xx`, [list recent documents](/docs/api-reference/documents/list) for the template and look for that file name before you render again.
- **Store the ID right away.** Once you have a document's ID, everything else (retrieving, waiting, downloading) is a `GET` that is safe to retry.
- **Shorten the window.** With `async: true` the request returns as soon as the payload is validated, so a dropped connection during a slow render can't leave you without the document ID.
```ts title="render-once.ts"
import Druckling, { APIConnectionError, ServerError } from "@druckling/sdk";
const druckling = new Druckling();
export async function renderInvoice(number: string, data: Record) {
const filename = `${number}.pdf`;
try {
return await druckling.documents.create({ template: "invoice-standard", filename, data });
} catch (error) {
if (!(error instanceof APIConnectionError || error instanceof ServerError)) throw error;
const recent = await druckling.documents.list({ template: "invoice-standard", limit: 20 });
const existing = recent.data.find((doc) => doc.filename === filename && doc.status !== "failed");
if (existing) return druckling.documents.wait(existing.id);
return druckling.documents.create({ template: "invoice-standard", filename, data });
}
}
```
The same applies to [`POST /v1/batches`](/docs/api-reference/batches/create): sending it twice starts two batches.
### What the SDKs retry [#what-the-sdks-retry]
The SDKs retry up to 2 times by default. They resend a `POST` only when Druckling rejected it without rendering anything:
- `429 rate_limited` is retried for every method, including `POST /v1/documents`. A rate-limited request rendered nothing.
- `429 quota_exceeded` is never retried.
- `408`, `5xx`, timeouts and connection errors are retried for `GET` and `DELETE` only.
See [SDKs](/docs/sdks#retries) for backoff and configuration.
## Errors in the SDKs [#errors-in-the-sdks]
Each SDK raises one error class per kind of failure, all under one base class, and they carry the same information as the JSON body:
| What you get | TypeScript and Python | PHP |
| --- | --- | --- |
| Error code | `error.code` | `$e->errorCode` |
| HTTP status | `error.status` | `$e->status` |
| Offending field | `error.field` | `$e->field` |
| All field errors | `error.errors` | `$e->errors` |
| Failed document ID | `error.documentId` (TS), `error.document_id` (Python) | `$e->documentId` |
| Request ID | `error.requestId` (TS), `error.request_id` (Python) | `$e->requestId` |
`errors` combines `data.errors` and the `data.issues` of request validation errors, each as a field and a message. Classes by error:
| Error | TypeScript and Python | PHP |
| --- | --- | --- |
| `400 BAD_REQUEST`, `schema_validation_failed`, `validation_failed` | `ValidationError` | `ValidationException` |
| `unauthorized` | `AuthenticationError` | `AuthenticationException` |
| `forbidden` | `PermissionDeniedError` | `PermissionDeniedException` |
| `not_found` | `NotFoundError` | `NotFoundException` |
| `conflict`, `invalid_state` | `ConflictError` | `ConflictException` |
| `render_failed`, `render_timeout` | `RenderError` | `RenderException` |
| `rate_limited` | `RateLimitError` | `RateLimitException` |
| `quota_exceeded` | `QuotaExceededError`, a `RateLimitError` | `QuotaExceededException`, a `RateLimitException` |
| `5xx` | `ServerError` | `ServerException` |
| `payload_too_large` | `APIError` | `ApiException` |
| No response | `APIConnectionError`, or `APITimeoutError` on timeout | `ConnectionException`, or `TimeoutException` on timeout |
```ts tab="TypeScript"
import Druckling, { QuotaExceededError, ValidationError } from "@druckling/sdk";
const druckling = new Druckling();
try {
await druckling.documents.create({ template: "invoice-standard", data });
} catch (error) {
if (error instanceof ValidationError) {
for (const issue of error.errors) console.error(`${issue.field}: ${issue.message}`);
} else if (error instanceof QuotaExceededError) {
console.error("Quota used up:", error.message);
} else {
throw error;
}
}
```
```python tab="Python"
from druckling import QuotaExceededError, Druckling, ValidationError
client = Druckling()
try:
client.documents.create(template="invoice-standard", data=data)
except ValidationError as error:
for issue in error.errors:
print(f"{issue.field}: {issue.message}")
except QuotaExceededError as error:
print("Quota used up:", error.message)
```
```php tab="PHP"
use Druckling\Exception\QuotaExceededException;
use Druckling\Exception\ValidationException;
use Druckling\Druckling;
$druckling = new Druckling();
try {
$druckling->documents->create(template: 'invoice-standard', data: $data);
} catch (ValidationException $e) {
foreach ($e->errors as $issue) {
echo "{$issue->field}: {$issue->message}", PHP_EOL;
}
} catch (QuotaExceededException $e) {
echo 'Quota used up: ', $e->getMessage(), PHP_EOL;
}
```
The SDK pages cover each language's error classes in detail: [TypeScript](/docs/sdks/typescript), [Python](/docs/sdks/python), [PHP](/docs/sdks/php).
## Debugging [#debugging]
- Every request that gets past the API key check shows up in **Developers › Logs**, with its status and duration. Requests rejected for a missing or invalid key don't; requests rejected by the per-key rate limit do, with status `429`.
- Failed renders appear in **Documents** with their error, the offending field and the request body as received.
- Each response has an `x-vercel-id` header that identifies the request. The SDKs expose it as the error's request ID. Include it when you contact support.
# Plans and limits (/docs/concepts/plans-and-limits)
> Druckling's plans and prices, what counts toward your document quota, rate limits, and the size limits that apply to every request.
Every workspace is on one plan. The plan sets how many live documents you can render each month and each day, and a few features of the embedded editor. Everything else on this page, from rate limits to payload sizes, is the same on every plan. Renders with test keys are free and never limited by the quota.
## Plans [#plans]
Prices are net, in euros, and billed per document, whatever its page count.
| | Free | Starter | Pro | Business |
| --- | --- | --- | --- | --- |
| Monthly price | €0 | €9 | €29 | €99 |
| Yearly price | – | €90 | €290 | €990 |
| Live documents per month | 250 | 1,000 | 10,000 | 50,000 |
| Live documents per day | 100 | 1,000 | 10,000 | 50,000 |
| Test documents | Unlimited | Unlimited | Unlimited | Unlimited |
| Pages per document | 50 | 100 | 200 | 500 |
| File retention | 30 days | 30 days | 30 days | 30 days |
| Signed download links | Up to 7 days | Up to 7 days | Up to 7 days | Up to 7 days |
| Embedded editor without the "Powered by Druckling" mark | No | No | Yes | Yes |
| Assistant in the embedded editor | No | No | Yes | Yes |
Owners and admins choose and change the plan in **Settings › Billing**, billed monthly or yearly. A yearly plan costs ten times the monthly price. VAT is added at checkout where it applies, and you can enter your VAT ID for your invoices.
Every plan can use the [embedded editor](/docs/guides/embedded-editor). On Free and Starter it shows a small "Powered by Druckling" mark, and the assistant isn't offered inside it even if a session asks for it. In embedded editors, Druck, the AI assistant, appears as a neutral "Assistant" without Druckling branding.
## What counts toward your quota [#what-counts-toward-your-quota]
One live document that finishes rendering counts as one document, whether it's a PDF, a PNG or an XML e-invoice, and however many pages it has. That includes documents rendered through the API, the SDKs, the [MCP server](/docs/guides/mcp), [n8n](/docs/guides/n8n), each item of a [batch](/docs/guides/batches), and documents you retry from the dashboard in live mode.
These don't count:
- Anything rendered with a test key, or in **Test mode** in the dashboard. See [Test mode](/docs/concepts/test-mode).
- Failed documents, whether they failed validation or rendering.
- Previews and Test PDFs in the template editor.
- Reading documents, downloading files, and creating or opening share links.
A document counts toward the UTC day on which it finished rendering.
## When quotas reset [#when-quotas-reset]
Both counters follow UTC, not your billing date:
- The **daily** count resets at 00:00 UTC.
- The **monthly** count resets at 00:00 UTC on the first day of each month.
## When you reach a quota [#when-you-reach-a-quota]
Druckling checks the quota when it accepts a live render. Once the daily or monthly limit is used up, render requests fail with `429` until the counter resets or you upgrade. There are no overage charges.
```json title="429 Too Many Requests"
{
"defined": false,
"code": "QUOTA_EXCEEDED",
"status": 429,
"message": "Monthly limit of 250 documents reached on the Free plan; it resets on 2026-11-01. Upgrade in Settings › Billing for a higher limit. Test keys are never limited.",
"data": {
"code": "quota_exceeded",
"field": null,
"scope": "monthly",
"plan": "free",
"used": 250,
"limit": 250
}
}
```
`data.scope` is `daily` or `monthly`, and `used` and `limit` are that counter's values. The daily limit is checked first.
A live [batch](/docs/guides/batches) is checked as a whole: all of its items must fit in what's left today and this month, counting live documents that are still queued. If they don't, nothing is rendered, and `data` also has `requested` (the batch's items) and `reserved` (the documents already queued).
The SDKs never retry `quota_exceeded`; they raise a quota error right away. To keep developing when your live quota runs out, switch to a test key.
## Rate limits [#rate-limits]
### Per API key [#per-api-key]
Each API key can make 120 requests a minute. The minute starts with the key's first request; the 121st request within it gets `429`, and the count starts over when the minute is up. So steady traffic under 120 requests a minute is never blocked, however long it runs. The count is shared by all of Druckling's servers.
Every authenticated request counts, on every endpoint and for test keys too: renders, polls of `GET /v1/documents/{id}`, list calls, and calls made through the [MCP server](/docs/guides/mcp) with that key. Each key has its own count.
```json title="429 Too Many Requests"
{
"defined": false,
"code": "TOO_MANY_REQUESTS",
"status": 429,
"message": "Too many requests for this API key: the limit is 120 a minute. Retry in 18 s.",
"data": { "code": "rate_limited", "field": null, "retryAfter": 18, "limit": 120 }
}
```
The response says when the minute is up, in seconds, both in the `Retry-After` header and in `data.retryAfter`. The SDKs read the header and wait for you. To stay under the limit, follow documents with [webhooks](/docs/guides/webhooks) instead of polling, and render large jobs as one [batch](/docs/guides/batches) instead of one request per document.
### Other limits [#other-limits]
A few more limits protect shared capacity. They're counted per server instance, so treat the numbers as approximate.
| What | Limit | Response |
| --- | --- | --- |
| Creating [embedded editor sessions](/docs/guides/embedded-editor) | About 60 a minute per workspace | `429 rate_limited`, with the seconds to wait in `data.retryAfter` |
| Requests from one embedded editor session (saves, previews) | About 600 a minute | `429 rate_limited`, with `data.retryAfter` |
| Druck (AI assistant) turns | About 30 a minute per workspace, and about 10 a minute per embedded editor session | `429` with a `Retry-After` header |
| Render capacity | When too many renders are waiting on one server | `429 rate_limited`, "The render engine is busy; retry shortly" |
| Opening [share links](/docs/concepts/share-links) | About 120 a minute per IP address | `429` page with a `Retry-After` header |
A render rejected because the engine is busy is recorded as a `failed` document with `error.code: "rate_limited"`. It produced no file and didn't count toward your quota, so sending the request again after a short pause is safe. An asynchronous render that hits this limit ends up `failed` the same way.
When the REST API (`/v1`) knows how long you should wait, it sends a `Retry-After` header and the same number of seconds in `data.retryAfter`.
## Payload and render limits [#payload-and-render-limits]
These limits apply on every plan.
| Limit | Value | When exceeded |
| --- | --- | --- |
| Size of a document's `data` | 1,000,000 bytes as JSON | `413 payload_too_large` |
| Items in any array of `data` | 10,000 | `413 payload_too_large`, with `field` set to the array's path |
| Nesting depth of `data` | 32 levels | `422 validation_failed` |
| `filename` | 200 characters | `400 BAD_REQUEST` |
| Pages per document | Your plan's limit (50 to 500, see above) | `422 render_failed`, with the page count in `data.pages` and the limit in `data.limit` |
| Typesetting time | 10 seconds | `504 render_timeout` |
| Images per document | 20 distinct image URLs | Images beyond the 20th render as placeholders |
| Size of one image | 5 MB, fetched within 4 seconds | The image renders as a placeholder |
| Items per batch | 1 to 1,000 | `400 BAD_REQUEST` |
| Size of a batch's `items` | 4 MB as JSON | `413 payload_too_large`, with `field: "items"` |
| Active share links per document | 20 | `409 conflict` |
| Share link lifetime | 1 to 30 days | `400 BAD_REQUEST` |
| Webhook endpoints per workspace | 20 | `409 conflict` |
| Embedded editor session lifetime | 60 seconds to 1 hour | `400 BAD_REQUEST` |
Druckling checks the size, array and nesting limits of `data` when the document renders. A synchronous request gets the error as its response, and the document is recorded as `failed`. For an asynchronous request the error shows up on the `failed` document (for example `error.code: "payload_too_large"`), not on the request.
Images are fetched while the document renders. Druckling only fetches public `https://` URLs that serve PNG, JPEG, GIF, SVG or WebP. An image that is missing, too large, too slow or of another type renders as a placeholder; the document still renders.
## Where to see your usage [#where-to-see-your-usage]
**Settings › Usage** shows this month's and today's live documents against your limits, when the monthly count resets, and your plan's retention and link lifetimes. Test documents are listed as unlimited.
To change plans, go to **Settings › Billing**.
## Next steps [#next-steps]
Develop and test without using your quota.
Every error code, and which ones are safe to retry.
Render up to 1,000 documents with one request.
# Share links (/docs/concepts/share-links)
> Give anyone a public, expiring link to a rendered document, without an account or an API key.
A share link is a public, unguessable URL for one rendered document. Whoever has it can open the file in a browser, with no Druckling account and no API key, until the link expires or you revoke it. Use share links to send an invoice to a customer, or to let someone outside your workspace review a contract.
Every rendered document already has a signed download [`url`](/docs/concepts/documents#download-the-file). A share link is the better choice when a person, not your code, opens the file:
| | Signed `url` | Share link |
| --- | --- | --- |
| Lifetime | Up to 7 days | 1 to 30 days, 7 by default |
| Revocable | No | Yes, effective immediately |
| Shown | On every read of the document | Once, when you create it |
| File name | The link's path ends in the document ID | Served under the document's `filename` |
Both stop working when the document's file is deleted at the end of [retention](/docs/concepts/documents#retention).
The SDKs don't cover share links yet. Call the endpoints below directly with the same API key.
## Create a share link [#create-a-share-link]
Send [`POST /v1/documents/{id}/share_links`](/docs/api-reference/share-links/create) with an optional `expires_in_days`, a whole number from 1 to 30 (default 7):
```bash
curl https://druckling-nine.vercel.app/v1/documents/pdf_8Qw2kLm3nP0aB1cD/share_links \
-H "Authorization: Bearer $DRUCKLING_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "expires_in_days": 14 }'
```
The answer is `201 Created` with the link:
```json title="Response"
{
"id": "shl_4Fq9LmZ2xR8tKpWc",
"object": "share_link",
"document": "pdf_8Qw2kLm3nP0aB1cD",
"url": "https://druckling-nine.vercel.app/s/k3J9vQ2xLm8RtY5wP1aZc7Nf0bHdx9Qa",
"hint": "x9Qa",
"status": "active",
"expires_at": "2026-11-10T10:02:17.551Z",
"revoked_at": null,
"test_mode": true,
"created_at": "2026-10-27T10:02:17.551Z"
}
```
What to expect:
- **Only rendered documents can be shared.** A document that is `queued`, `rendering` or `failed` answers `409` with code `invalid_state` ("Only rendered documents can be shared"). So does an expired one ("This document's file was deleted after the retention period").
- **The link never outlives the file.** `expires_at` is the earlier of `expires_in_days` from now and the document's own `expires_at`. Asking for 30 days on a document rendered 25 days ago gives a link that works for about 5 more days, without an error, so check `expires_at` in the response.
- **Out-of-range lifetimes are rejected.** An `expires_in_days` below 1, above 30 or with a fraction fails with `400 BAD_REQUEST`.
- **A document can have up to 20 active links.** The 21st answers `409` with code `conflict`. Revoke one first.
- **Any API key works.** Both Render only and Full access keys can create, list and revoke share links.
- **Links are free.** Creating and opening share links doesn't count toward your [plan's quota](/docs/concepts/plans-and-limits).
### The link is shown once [#the-link-is-shown-once]
Druckling stores only a SHA-256 hash of each link, never the link itself, so `url` appears in the create response and nowhere else. Listing or revoking returns `url: null`. Store the link when you create it, or create a new one if you lose it.
`hint` holds the link's last four characters, so you and your users can tell links apart (the dashboard shows it as `…x9Qa`).
## What visitors see [#what-visitors-see]
Opening the link streams the file itself, with no Druckling page around it:
- A PDF or PNG opens in the browser, like any file served inline.
- An XML e-invoice is shown as XML, in a sandbox that keeps it from running anything.
- Add `?download` to the link (for example `https://druckling-nine.vercel.app/s/k3J9…x9Qa?download`) to have the browser save the file instead of showing it.
The file is served under the document's `filename`. Responses tell search engines not to index the file, tell browsers and proxies not to cache it, and send no referrer. Nothing in the response names your workspace.
When a link can't be served, the visitor gets a short HTML page instead:
| Status | Page | When |
| --- | --- | --- |
| `404` | Link not found | The link is incomplete or wrong, or it was deleted after it expired. |
| `410` | This link was revoked | You revoked the link. |
| `410` | This link has expired | The link reached its `expires_at`, or the document's file was deleted. |
| `429` | Too many requests | Too many requests from one IP address, about 120 a minute. The response has a `Retry-After` header. |
Expired links don't answer `410` forever. A daily cleanup deletes every link whose `expires_at` has passed, revoked links included. From then on the link answers `404`, and it no longer appears when you list the document's links.
## List a document's links [#list-a-documents-links]
[`GET /v1/documents/{id}/share_links`](/docs/api-reference/share-links/list) returns every link of the document that hasn't been cleaned up yet, newest first:
```bash
curl https://druckling-nine.vercel.app/v1/documents/pdf_8Qw2kLm3nP0aB1cD/share_links \
-H "Authorization: Bearer $DRUCKLING_API_KEY"
```
```json title="Response"
{
"object": "list",
"data": [
{
"id": "shl_4Fq9LmZ2xR8tKpWc",
"object": "share_link",
"document": "pdf_8Qw2kLm3nP0aB1cD",
"url": null,
"hint": "x9Qa",
"status": "active",
"expires_at": "2026-11-10T10:02:17.551Z",
"revoked_at": null,
"test_mode": true,
"created_at": "2026-10-27T10:02:17.551Z"
}
]
}
```
A link's `status` is worked out each time you read it:
| `status` | Meaning |
| --- | --- |
| `active` | The link works. |
| `expired` | The link reached its `expires_at`. |
| `revoked` | You revoked it; `revoked_at` says when. |
## Revoke a link [#revoke-a-link]
[`DELETE /v1/documents/{id}/share_links/{share_link_id}`](/docs/api-reference/share-links/revoke) stops the link immediately. The next visit gets `410`.
```bash
curl -X DELETE https://druckling-nine.vercel.app/v1/documents/pdf_8Qw2kLm3nP0aB1cD/share_links/shl_4Fq9LmZ2xR8tKpWc \
-H "Authorization: Bearer $DRUCKLING_API_KEY"
```
The response is the link with `status: "revoked"` and `revoked_at` set. Revoking a link twice is fine and keeps the first `revoked_at`. An unknown link, or a link that belongs to another document, answers `404`.
A revoked link can't be restored, and no link can be extended. Create a new link instead.
## In the dashboard [#in-the-dashboard]
Open a rendered document in **Documents**. Under **Share links**, pick a lifetime in **Expires after** (1, 7, 14 or 30 days) and click **Create link**. Copy the link right away with **Copy**: like the API, the dashboard shows it only once. The list below shows each link's hint, status and expiry, with **Revoke** next to the active ones.
## Test mode [#test-mode]
Share links work the same way for [test documents](/docs/concepts/test-mode). A link's `test_mode` matches the document it points to.
## Security [#security]
Treat a share link like the file itself:
- **Links can't be guessed.** The part after `/s/` is 32 random characters (192 bits), and Druckling keeps only its hash.
- **Anyone with the link can open the file.** Send it only to the person who should see the document, over a channel you trust. Forwarding the link forwards access.
- **Keep lifetimes short.** Pick the shortest expiry that works for the recipient.
- **Revoke when in doubt.** Revoke a link as soon as it's no longer needed, or if it may have leaked.
- **Keep links out of logs.** Refer to links by `id` or `hint` in your own logs and support tools, not by the full URL.
## Next steps [#next-steps]
Formats, retention and signed download links.
Every field of the share link endpoints.
# Template strings (/docs/concepts/template-strings)
> The syntax Druckling templates use to insert data, format numbers, amounts and dates with filters, and style text.
Most texts in a template are template strings: paragraphs, headings, table cells and totals, barcode values and signer names. A template string is literal text with `{{bindings}}` that insert data, filters that format it, and a few formatting marks.
```text
Hello **{{customer.name}}**, your total is {{totals.amount | money}}.
Due {{invoice.due_date | date:"[day].[month].[year]"}} · [Pay online](https://pay.example.com)
```
With the `invoice-standard` sample data, this prints "Hello **Northwind Ltd.**, your total is $10,692.00." on the first line and "Due 22.11.2026 · Pay online" on the second, with "Pay online" as a link.
## Bindings [#bindings]
`{{path}}` inserts the value at a dotted path of the payload. Spaces inside the braces are fine: `{{ customer.name }}` works too.
- A path is made of names with letters, digits and underscores, separated by dots. A name can't start with a digit, so a binding can't index into a list; print list items with a [table](#conditional-blocks-and-repeating-rows).
- Every binding must point to a [declared variable](/docs/concepts/variables). Otherwise the editor shows an error and you can't publish.
- In a table cell, bind the row through the table's row alias, for example `{{item.qty}}`.
Data is always inserted as plain text:
| Value in the payload | Prints as |
| --- | --- |
| `"Northwind Ltd."` | `Northwind Ltd.` |
| `4800`, `4800.5` | `4800`, `4800.5` (use a [filter](#filters) to format numbers) |
| `true`, `false` | `true`, `false` |
| `["a", "b"]` | `a, b` |
| an object | nothing (bind one of its fields) |
| a string with a line break (`"12 Pier St\nLeeds"`) | two lines |
### Missing values [#missing-values]
A missing key or `null` prints nothing, with or without a filter, and doesn't fail the render. If the variable is required, the request fails [validation](/docs/concepts/variables#validation-on-every-render) before anything renders. To print a fallback, use the [`default`](#default) filter.
## Filters [#filters]
A filter formats the bound value: `{{path | filter}}`, or `{{path | filter:"argument"}}` for filters that take an argument. The quotes around the argument are optional.
Each binding takes at most one filter. Chaining, as in `{{name | upper | default:"n/a"}}`, is a validation error, and so is an unknown filter name.
| Filter | Argument | What it does |
| --- | --- | --- |
| [`money`](#money) | Currency code, such as `"EUR"` (default: the template's currency) | Formats a number as an amount with a currency symbol. |
| [`date`](#date) | Date pattern (default: depends on the language) | Formats a `YYYY-MM-DD` date. |
| [`number`](#number) | Decimals: `"2"` or a range such as `"0-2"` (default: `0`) | Formats a number with grouping and decimals. |
| [`percent`](#percent) | Decimals (default: `0`) | Multiplies by 100 and adds `%`. |
| [`upper`](#upper-and-lower) | | Converts to uppercase. |
| [`lower`](#upper-and-lower) | | Converts to lowercase. |
| [`default`](#default) | Fallback text | Prints the fallback when the value is missing, `null` or empty. |
Filters that expect a number also accept numeric strings such as `"12.50"`. A value they can't format prints unchanged, so `{{status | money}}` with `"n/a"` prints `n/a`.
The examples below were produced by the rendering engine. Unless a row says otherwise, the language is English (`en`) and the template's currency is USD. "nbsp" stands for a no-break space and "nnbsp" for a narrow no-break space.
### money [#money]
Prints two decimals (none for JPY and KRW), the language's separators and the currency's symbol.
| Template string | Value | Language, currency | Output |
| --- | --- | --- | --- |
| `{{amount \| money}}` | `4800` | en, USD | `$4,800.00` |
| `{{amount \| money}}` | `-12.5` | en, USD | `-$12.50` |
| `{{amount \| money:"EUR"}}` | `4800` | en | `€4,800.00` |
| `{{amount \| money:"GBP"}}` | `4800` | en | `£4,800.00` |
| `{{amount \| money:"CHF"}}` | `4800` | en | `CHF 4,800.00` (nbsp) |
| `{{amount \| money:"JPY"}}` | `4800` | en | `¥4,800` |
| `{{amount \| money}}` | `4800` | de, EUR | `4.800,00 €` (nbsp) |
| `{{amount \| money}}` | `4800` | fr, EUR | `4 800,00 €` (nnbsp, nbsp) |
| `{{amount \| money:"PLN"}}` | `1234.567` | pl | `1.234,57 zł` (nbsp) |
| `{{amount \| money:"XYZ"}}` | `4800` | en | `XYZ 4,800.00` (nbsp) |
- Without an argument, `money` uses the currency set in the editor under **Document › Output › Currency** (USD by default). In an e-invoice template it uses the payload's `invoice.currency`.
- Languages with a decimal comma put the symbol after the amount; the others put it before.
- Symbols are built in for USD ($), EUR (€), GBP (£), JPY and CNY (¥), INR (₹), KRW (₩), CAD (CA$), AUD (A$), NZD (NZ$), BRL (R$), MXN (MX$), CHF (CHF), SEK, NOK and DKK (kr), PLN (zł), CZK (Kč), TRY (₺) and ZAR (R). Any other code prints as is, so write codes in uppercase.
### date [#date]
Formats a value that starts with `YYYY-MM-DD`. Anything after the date, such as a time, is ignored.
| Template string | Value | Language | Output |
| --- | --- | --- | --- |
| `{{due \| date}}` | `"2026-11-22"` | en | `Nov 22, 2026` |
| `{{due \| date}}` | `"2026-11-22"` | de, pl and most others | `22.11.2026` |
| `{{due \| date}}` | `"2026-11-22"` | fr, es, it, pt | `22/11/2026` |
| `{{due \| date}}` | `"2026-11-22"` | nl | `22-11-2026` |
| `{{due \| date}}` | `"2026-11-22T14:30:00Z"` | en | `Nov 22, 2026` |
| `{{due \| date:"[day].[month].[year]"}}` | `"2026-11-22"` | any | `22.11.2026` |
| `{{due \| date:"[month repr:long] [day], [year]"}}` | `"2026-11-22"` | any | `November 22, 2026` |
| `{{due \| date:"[weekday], [day padding:none] [month repr:short] [year]"}}` | `"2026-11-22"` | any | `Sunday, 22 Nov 2026` |
| `{{due \| date:"[day padding:none]. [month padding:none]. [year]"}}` | `"2026-03-05"` | any | `5. 3. 2026` |
| `{{due \| date:"[year repr:last_two]"}}` | `"2026-11-22"` | any | `26` |
| `{{due \| date}}` | `"soon"` | any | `soon` |
Patterns use [Typst's date format syntax](https://typst.app/docs/reference/foundations/datetime/): components such as `[day]`, `[month]`, `[year]` and `[weekday]` in square brackets, with modifiers such as `padding:none` or `repr:long`. Text outside the brackets prints as written.
- Month and weekday names are always English, whatever the render language: `[month repr:long]` prints `November` in a German document too. For other languages, use numeric patterns or the default.
- An unknown component, such as `[foo]`, makes the render fail with `render_failed`. Publishing renders the sample data, so it catches this as long as the sample data has a date in that field.
The schema only checks that a date starts with `YYYY-MM-DD`. A value such as `2026-02-31` passes validation, but formatting it with `date` fails the render with `render_failed` ("date is invalid"). Validate dates in your own code before you send them.
### number [#number]
| Template string | Value | Language | Output |
| --- | --- | --- | --- |
| `{{x \| number}}` | `1234.5` | en | `1,235` |
| `{{x \| number:"2"}}` | `1234.5` | en | `1,234.50` |
| `{{x \| number:"2"}}` | `1234.5` | de | `1.234,50` |
| `{{x \| number:"2"}}` | `1234.5` | fr | `1 234,50` (nnbsp) |
| `{{x \| number:"0-2"}}` | `1234.5` | en | `1,234.5` |
| `{{x \| number:"0-2"}}` | `19` | en | `19` |
| `{{x \| number:"0-2"}}` | `5.5` | de | `5,5` |
| `{{x \| number:"1-2"}}` | `5.555` | en | `5.56` |
| `{{x \| number:"1"}}` | `-1234.5` | en | `-1,234.5` |
| `{{x \| number}}` | `2.5` | en | `3` |
- Without an argument, `number` rounds to a whole number. Halves round away from zero.
- `"2"` prints exactly two decimals. A range such as `"0-2"` prints up to two and drops trailing zeros, which suits VAT rates like 19 and 5.5.
- The argument is a single digit (0 to 9) or a range of two digits. Anything else, such as `"10"`, counts as no argument.
### percent [#percent]
| Template string | Value | Language | Output |
| --- | --- | --- | --- |
| `{{rate \| percent}}` | `0.19` | en | `19%` |
| `{{rate \| percent:"1"}}` | `0.055` | en | `5.5%` |
| `{{rate \| percent:"1"}}` | `0.055` | de | `5,5%` |
| `{{rate \| percent}}` | `19` | en | `1,900%` |
`percent` expects a fraction and multiplies it by 100. If your data already holds percentages, such as a VAT rate of `19`, use `{{rate | number:"0-2"}}%` instead.
### upper and lower [#upper-and-lower]
| Template string | Value | Output |
| --- | --- | --- |
| `{{name \| upper}}` | `"Ada Lovelace"` | `ADA LOVELACE` |
| `{{name \| upper}}` | `"straße"` | `STRASSE` |
| `{{code \| lower}}` | `"ADA"` | `ada` |
### default [#default]
| Template string | Value | Output |
| --- | --- | --- |
| `{{po \| default:"n/a"}}` | missing or `null` | `n/a` |
| `{{po \| default:"n/a"}}` | `""` | `n/a` |
| `{{po \| default:"n/a"}}` | `0` | `0` |
| `{{po \| default:"n/a"}}` | `false` | `false` |
| `{{po \| default:"n/a"}}` | `"PO-77"` | `PO-77` |
The fallback is plain text. It can't contain `|` or `}}`.
## Language and number formats [#language-and-number-formats]
The render's [`language`](/docs/guides/languages), or the template's default language when a request names none, decides the separators and the default date format:
| Languages | Numbers | Default date |
| --- | --- | --- |
| `en` | `1,234.50` | `Nov 22, 2026` |
| `fr` | `1 234,50` (nnbsp) | `22/11/2026` |
| `es`, `it`, `pt` | `1.234,50` | `22/11/2026` |
| `nl` | `1.234,50` | `22-11-2026` |
| `bg`, `ca`, `cs`, `da`, `de`, `el`, `et`, `fi`, `hr`, `hu`, `is`, `lb`, `lt`, `lv`, `nb`, `no`, `pl`, `ro`, `ru`, `sk`, `sl`, `sv`, `tr`, `uk` | `1.234,50` | `22.11.2026` |
| Any other code, such as `ga` (Irish) or `mt` (Maltese) | `1,234.50` | `22.11.2026` |
The language changes how an amount is formatted, not its currency: `money` without an argument always uses the template's currency.
## Formatting marks [#formatting-marks]
| Write | Result |
| --- | --- |
| `**bold**` | **bold** |
| `*italic*` | *italic* |
| `**bold *and italic***` | **bold *and italic*** |
| `[label](https://example.com)` | A link. The URL must start with `https://`, `http://` or `mailto:`. |
| A line break | A line break in the PDF. |
Marks apply to bindings inside them: `**{{customer.name}}**` prints the name in bold, and `[Invoice {{invoice.number}}](https://example.com/pay)` makes it part of the link text.
- A link's URL is used exactly as written, bindings included: `[Pay](https://pay.example.com/{{invoice.number}})` links to a URL that literally contains `{{invoice.number}}`. Links can't be built from data. A [QR code](/docs/concepts/variables#images-barcodes-and-qr-codes) can.
- If the URL doesn't start with one of the allowed schemes, the whole `[label](url)` prints as text.
- An unclosed `**` or `*` is a validation error. A lone asterisk, as in `Prices marked * include VAT`, opens italic text, so escape it: `Prices marked \* include VAT`.
## Escaping [#escaping]
A backslash prints the next character literally:
| Write | Prints |
| --- | --- |
| `\{{name}}` | `{{name}}` |
| `\*` | `*` |
| `\[` | `[` |
| `\\` | `\` |
Single braces, and `}}` without an opening `{{`, need no escaping. When you send a template string inside JSON, for example through the [MCP server](/docs/guides/mcp), escape the backslash itself: `"\\{{name}}"`.
Data never needs escaping. A customer name such as `**ACME** {{x}}` prints exactly like that, without bold and without a binding.
## Where template strings work [#where-template-strings-work]
| Field | Template string | Notes |
| --- | --- | --- |
| Text and heading content | Yes | |
| Table cell | Yes | The row alias is in scope: `{{item.qty}}`. |
| Table totals value | Yes | Binds top-level fields such as `{{totals.amount \| money}}`, not the row alias. |
| QR / Barcode value | Yes | Evaluated to plain text before the code is drawn: marks are dropped, `money` prints the currency code (`USD 4,800.00`) and `date` leaves the value unformatted. |
| Signature signer | Yes | For example `{{landlord.name}}`. |
| Table column header, totals label, empty-table text | No | Plain text, printed as written. |
| Signature label, chart title, image alt text | No | Plain text. |
| Document title, watermark | No | Plain text. |
| Page number format | No | Takes the placeholders `{page}` and `{total}`. |
| Image source | No | Choose a fixed URL or an image variable on the block. |
| Batch `filename_pattern` | Partly | Supports `{{path}}` with the `upper`, `lower` and `default` filters; other filters insert the raw value. See [Batches](/docs/guides/batches). |
The `filename` of a single [`POST /v1/documents`](/docs/api-reference/documents/create) request is used as written, without bindings.
## Conditional blocks and repeating rows [#conditional-blocks-and-repeating-rows]
Template strings have no `if` or loop syntax. Blocks do the job instead.
**Repeating rows.** A Table block repeats one row per item of a list variable (its `each`, such as `line_items`) and names the current row with an alias (`item` by default). Tables can sort rows by a field, hide themselves or show a text when the list is empty, and end with totals rows.
**Conditional blocks.** Any block can have a visibility condition, set under **Visibility** in the block's settings. The block prints only when the condition holds. The `invoice-standard` starter uses one to print the payment QR code only when `payment.url` is not empty.
| Condition | API name | True when |
| --- | --- | --- |
| is not empty | `notEmpty` | The value is present and, for text, lists and objects, not empty. |
| exists | `exists` | The value is present and not `null`. |
| is true / non-zero | `truthy` | The value isn't `null`, `false`, `""` or `0`, and isn't an empty list or object. |
| equals | `eq` | The value equals the given value, compared as text, so `3` equals `"3"`. |
| does not equal | `neq` | The opposite of `eq`. |
| is greater than, is at least, is less than, is at most | `gt`, `gte`, `lt`, `lte` | Both sides are numbers (or numeric strings) and the comparison holds. Otherwise false. |
A block has one condition, on a payload field such as `payment.url`; it can't test a field of a table row. To require two conditions, put the block in a Box with its own condition: the box's condition and the block's both have to hold.
## Safety [#safety]
Template strings can't inject code into the rendering engine. The literal text of a template reaches the Typst engine only as escaped string literals, and payload data never becomes part of the template source: it's read from a separate JSON file and printed as plain text. A customer name such as `#set page(paper: "a7")` prints as those characters and changes nothing about the layout.
Declare the fields your bindings read.
Render one template in several languages.
# Templates (/docs/concepts/templates)
> What a Druckling template contains, how its draft becomes immutable published versions, and how to read templates through the API.
A template is a document layout plus the data contract it expects. You design it in the visual editor, publish it, and then render documents from it by sending its slug and a JSON payload to [`POST /v1/documents`](/docs/api-reference/documents/create).
## What a template contains [#what-a-template-contains]
Every template is one document with these parts:
- **Page setup**: paper size and orientation, margins in millimeters, a header and footer that repeat on every page, an optional first-page header (for letterheads) and an optional text watermark.
- **Document settings**: title and author (written to the PDF metadata), fonts, base text size, line spacing, default language, hyphenation, justification, text and accent colors, the currency the `money` filter uses, the PDF standard and e-invoicing.
- **Variables**: the fields the payload can or must contain. They define the template's [JSON Schema](/docs/concepts/variables).
- **Sample data**: an example payload, used for previews and checked when you publish.
- **Blocks**: the content, in order.
- **Translations**: texts for languages other than the default one. See [Languages](/docs/guides/languages).
### Blocks [#blocks]
| Block | What it does |
| --- | --- |
| Text | A paragraph with [template strings](/docs/concepts/template-strings): bound values, bold, italic and links. |
| Heading | A level 1, 2 or 3 heading. |
| Table | Repeats one row per item of a list variable, with a repeating header, page-break rules, sorting and optional totals rows. |
| Image | An image from a fixed https URL or from an image variable. Shows a placeholder box when there's no image. |
| Chart | A bar or line chart over a list variable. |
| QR / Barcode | A QR code, Code 128, EAN-13 or Data Matrix code whose value is a template string. |
| Signature | A signature line with a label, an optional signer name and an optional date line. |
| Page no. | A page counter such as `Page {page} of {total}`, usually in the footer. |
| Divider | A horizontal rule. |
| Spacer | Vertical space, in points. |
| Page break | Starts a new page. |
| Box | A container with an optional fill and border, for notes and callouts. |
| Columns | Up to six side-by-side columns, each holding its own blocks. |
Every block also has style settings (alignment, size, weight, italic, color, font, space above and below, keep together on one page) and an optional visibility condition that shows it only when the payload meets it. See [Conditional blocks](/docs/concepts/template-strings#conditional-blocks-and-repeating-rows).
## Slugs [#slugs]
API requests identify a template by its slug, for example `invoice-standard`. Druckling derives the slug from the name when you create the template: it lowercases the name, removes accents, turns everything other than letters and digits into dashes and keeps at most 56 characters. `Invoice — Standard (EU)` becomes `invoice-standard-eu`. If the slug is taken, Druckling appends `-2`, `-3` and so on.
A slug is 2 to 63 characters long, uses lowercase letters, digits and dashes, starts with a letter or digit, and is unique within the workspace. Test and live API keys see the same templates, so a slug works with both `dr_test_…` and `dr_live_…` keys.
## Kinds [#kinds]
Each template has a kind: `invoice`, `certificate`, `report`, `ticket`, `agreement`, `packing` or `custom`. A template made from a starter takes the starter's kind; a blank template is `custom`. The kind only labels the template in the dashboard. It doesn't change how it renders, and the API doesn't return it.
## Starters [#starters]
Starters are ready-made templates with variables and sample data. Create a template from one in **Templates › New template**, which also offers a blank A4 page, a template built by Druck, the AI assistant, from an image or sketch, and **Import from PDF**.
| Slug | Name | What it is | In new workspaces |
| --- | --- | --- | --- |
| `invoice-standard` | Invoice | A4 invoice with line items, totals and a payment QR code. | Created and published as version 1 |
| `course-certificate` | Course certificate | Landscape A4 certificate with a signature line and a verification QR code. | Created as a draft |
| `quarterly-report` | Quarterly report | Summary, revenue bar chart and KPI table. | Created as a draft |
| `event-ticket` | Event ticket | Landscape A6 ticket with a scannable QR code. | Created as a draft |
| `rental-agreement` | Rental agreement | Multi-page contract with clauses and two signature lines. | Created as a draft |
| `packing-slip` | Packing slip | A5 slip with order items and a Code 128 barcode. | Created as a draft |
| `rechnung-zugferd` | Rechnung (ZUGFeRD) | German EN 16931 e-invoice (ZUGFeRD / Factur-X, PDF/A-3b) with the §14 UStG details and a GiroCode. | Not created; add it from **New template** |
| `facture-factur-x` | Facture (Factur-X) | French EN 16931 e-invoice (Factur-X, PDF/A-3b) with the mandatory mentions. | Not created; add it from **New template** |
A new workspace starts with the first six. Only `invoice-standard` is published, so it's the only one you can render right away; publish the others before you render them. The e-invoice starters are covered in [E-invoicing](/docs/guides/e-invoicing).
## Editing templates [#editing-templates]
### Visual editor [#visual-editor]
Open a template under **Templates** and click **Open editor**. The left panel holds the **Blocks** palette, the **Layers** tree and the **Data** tab with variables and sample data. The right panel edits the selected **Block**, the **Page** and the **Document**. The canvas is rendered by the same Typst engine as the API, with your sample data, and a switch above it shows either the variable names or the sample values.
**Test PDF** renders the draft with its sample data into a PDF you can download. It doesn't create a document or count toward your plan.
### Druck [#druck]
The editor comes with Druck, the AI assistant. You can ask Druck for changes in plain language. Druck reads the draft, its variables and sample data, and it can:
- add, restyle, move and remove blocks, declare variables and fill in sample data,
- lay out the draft with the real engine to answer questions such as "will 40 line items fit on two pages?",
- check a payload against the template's schema,
- translate the template into another language,
- read this template's recent renders to explain a failure,
- rebuild a layout from an attached image, sketch or PDF.
Druck proposes changes as a card that you **Apply** or **Discard**. Nothing changes until you apply it, and applied changes land in the draft like your own edits.
### Other ways to edit [#other-ways-to-edit]
- An AI agent can create, edit, preview and publish templates through the hosted [MCP server](/docs/guides/mcp) with a **Full access** API key.
- Your own users can edit a template inside your product with the [embedded editor](/docs/guides/embedded-editor).
The `/v1` REST API reads templates but doesn't edit them.
## Drafts, versions and publishing [#drafts-versions-and-publishing]
A template has one editable **draft** and any number of published **versions**. Renders always use a version, never the draft.
### The draft [#the-draft]
The editor saves the draft continuously while you work. Each save applies a set of edit operations to a numbered revision of the draft and increments it. If someone else saved the draft since the revision your change was based on, the save is rejected with `stale_revision` (409). The editor handles this for you: it loads the newer draft and reapplies your changes on top. An agent working through the MCP server gets the error and has to re-read the draft before it retries.
### Publishing [#publishing]
Click **Publish** in the editor (**Publish changes** once a version exists), optionally describe what changed, and confirm. The note can be up to 500 characters and shows in the template's **Versions** tab.
Publishing creates the next version number (1, 2, 3, …) as an immutable snapshot of the document, its JSON Schema and its required fields. Before it does, Druckling checks the draft:
1. The draft has no validation errors. Warnings don't block publishing; see [Validation issues](#validation-issues).
2. The sample data matches the template's variables.
3. The draft renders with the sample data, including the checks of its PDF standard.
If a check fails, nothing is published and you get the reason: `validation_failed` (422) for the first two, `render_failed` (422) for the third, and `stale_revision` (409) if the draft changed while publishing.
A template's `status` is `draft` until it's published for the first time and `published` from then on, even while the draft has newer changes. `latest_version` is the newest version number, or `null` before the first publish.
### Which version a render uses [#which-version-a-render-uses]
[`POST /v1/documents`](/docs/api-reference/documents/create) and [`POST /v1/batches`](/docs/api-reference/batches/create) take an optional `version`: a version number, or `"latest"` (the default).
- `"latest"` resolves when the request arrives, and the document records the number it used in `version`. An asynchronous render keeps that number even if you publish again before it runs.
- Editing the draft never changes what renders produce. Only publishing does, and only for requests that use `"latest"`.
- Pinned versions keep working after you publish newer ones.
```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",
"version": 1,
"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",
version: 1,
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",
version=1,
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"
documents->create(
template: 'invoice-standard',
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],
],
version: 1,
);
```
Pin the version your integration was built against. You can then publish freely, and move the pin when your code sends what the new version expects, for example a field that became required.
Rendering a template that was never published fails with 404 `not_found` and `field: "template"`, with the message `Template quarterly-report has no published version yet; publish it first`. A version number that doesn't exist fails with 404 `not_found` and `field: "version"`, for example `Template invoice-standard has no version 7`. See [Errors](/docs/concepts/errors).
## Validation issues [#validation-issues]
The editor checks the draft as you edit and lists the problems in the status menu above the canvas. Errors block publishing; warnings don't.
Errors include:
- a binding to a variable that isn't declared, such as `{{customer.phone}}`,
- template string syntax: an unclosed `{{`, an unknown filter, more than one filter in a binding, or an unclosed `**` or `*`,
- a table or chart over a variable that isn't a declared list, or an image bound to an undeclared variable,
- a visibility condition on an undeclared variable, or a comparison without a value,
- a variable declared twice, or two blocks with the same id,
- the rules of the chosen PDF standard, such as alt text on images for PDF/UA-1 and PDF/A-3a (see [Accessible PDFs](/docs/guides/accessible-pdfs)),
- e-invoicing settings that don't fit together, such as Factur-X without PDF/A-3 (see [E-invoicing](/docs/guides/e-invoicing)),
- translations that are too long or contain broken bindings.
Warnings include a binding to a whole object or list instead of one of its fields, a sort field or chart axis that isn't declared on the list, and texts that aren't translated yet (they print in the default language).
## Template settings [#template-settings]
Page and document settings are part of the draft, so a change takes effect for renders when you publish it.
| Setting | Where | Options |
| --- | --- | --- |
| Paper | **Page › Paper** | A4, A5, A6, Letter, Legal or a 4 × 6 in label, portrait or landscape. |
| Margins, header and footer | **Page** | Margins in millimeters; header, footer and first-page header blocks; watermark. |
| PDF standard | **Document › Output** | Standard PDF, PDF/A-2b, PDF/A-3b, PDF/A-3a or PDF/UA-1, one per template. See [Accessible PDFs](/docs/guides/accessible-pdfs). |
| E-invoice (EN 16931) | **Document › Output** | Factur-X / ZUGFeRD, XRechnung or Peppol BIS. See [E-invoicing](/docs/guides/e-invoicing). |
| Currency | **Document › Output** | The default currency of the `money` filter (USD unless you change it). See [Template strings](/docs/concepts/template-strings#money). |
| Language | **Document › Typography** and the language switcher above the canvas | A default language plus up to 30 more. See [Languages](/docs/guides/languages). |
## Duplicating a template [#duplicating-a-template]
**Duplicate** on the template page copies the current draft into a new template named after the original with `(copy)` appended, with the slug `-copy` (or `-copy-2`, …). The copy starts as an unpublished draft with no versions, so publish it before you render it. Documents rendered from the original stay with the original.
## Templates in the API [#templates-in-the-api]
Two read-only endpoints describe your templates. Both need the `templates:read` permission, which **Full access** keys have. A **Render only** key gets 403 `forbidden`. Create keys in **Developers › API keys**; see [Authentication](/docs/authentication).
- [`GET /v1/templates`](/docs/api-reference/templates/list) lists every template in the workspace, drafts included, most recently changed first. The list isn't paginated.
- [`GET /v1/templates/{slug}`](/docs/api-reference/templates/get) returns one template with its `json_schema` and `sample_data`.
`required_fields`, `language`, `languages`, `json_schema` and `sample_data` describe the latest published version, or the draft for a template that was never published. Unpublished draft changes don't show up until you publish.
```bash tab="cURL"
curl https://druckling-nine.vercel.app/v1/templates/invoice-standard \
-H "Authorization: Bearer $DRUCKLING_API_KEY"
```
```ts tab="TypeScript"
import Druckling from "@druckling/sdk";
const druckling = new Druckling();
const template = await druckling.templates.get("invoice-standard");
console.log(template.latest_version, template.required_fields);
```
```python tab="Python"
from druckling import Druckling
client = Druckling()
template = client.templates.get("invoice-standard")
print(template.latest_version, template.required_fields)
```
```php tab="PHP"
templates->get('invoice-standard');
echo $template->latestVersion, ' ', implode(', ', $template->requiredFields), PHP_EOL;
```
The response, with `json_schema` and `sample_data` shortened (the full schema is on [Variables and schema](/docs/concepts/variables#the-derived-json-schema)):
```json title="200 OK"
{
"id": "tpl_3Hk9QmZ1xT7pLw2V",
"object": "template",
"slug": "invoice-standard",
"name": "Invoice",
"status": "published",
"latest_version": 1,
"required_fields": [
"invoice.number",
"invoice.due_date",
"customer.name",
"customer.address",
"line_items[].description",
"line_items[].qty",
"line_items[].rate",
"line_items[].amount",
"totals.subtotal",
"totals.amount"
],
"language": "en",
"languages": ["en"],
"updated_at": "2026-10-27T09:12:44.512Z",
"json_schema": {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"customer": {
"type": "object",
"properties": {
"name": { "type": "string" },
"address": { "type": "string" }
},
"required": ["name", "address"]
}
},
"required": ["invoice", "customer", "line_items", "totals"]
},
"sample_data": {
"customer": { "name": "Northwind Ltd.", "address": "12 Pier St, Leeds" }
}
}
```
`required_fields` lists the required leaf fields. Fields of list items appear with `[]`, as in `line_items[].qty`: each item must have them.
Declare the data a template expects and validate payloads.
Bind values, format them with filters and style text.
Render templates synchronously or asynchronously.
# Test mode (/docs/concepts/test-mode)
> Build against test keys that render real documents for free and keep their data apart from live mode, then switch keys to go live.
Every Druckling workspace has two modes, live and test. Test mode lets you build and check an integration with real renders that cost nothing and never mix with your production data. The API key decides the mode: `dr_test_…` keys work in test mode, `dr_live_…` keys in live mode.
## What test mode changes [#what-test-mode-changes]
- **Renders are free.** Test renders never count toward your plan's daily or monthly documents, and quota checks are skipped, so a test request never fails with `429 quota_exceeded`. That includes [batches](/docs/guides/batches): a test batch doesn't have to fit in the documents you have left.
- **The output doesn't change.** Test documents are rendered exactly like live ones: no watermark, the same template version, the same PDF/A or PDF/UA settings and the same e-invoice XML. Files are kept for the same 30 days, and signed links work for the same 7 days.
- **Other limits still apply.** Rate limits, request size limits and payload validation work the same in both modes. See [Plans and limits](/docs/concepts/plans-and-limits).
## How the mode is chosen [#how-the-mode-is-chosen]
### In the API [#in-the-api]
The key's prefix is the only thing that decides the mode. There's no header or parameter to switch it, so the same code runs in test and live mode: only the key changes. You create keys of either mode under **Developers › API keys**; see [Authentication](/docs/authentication).
The SDKs tell you which mode a client is in: `druckling.mode` in TypeScript and `client.mode` in Python return `"test"` or `"live"` based on the key.
### In the dashboard [#in-the-dashboard]
The **Test mode** switch at the bottom of the sidebar chooses which data the dashboard shows. While it's on, a colored line runs along the top of the page, and documents, batches, request logs and the numbers on **Overview** and **Metrics** come from test mode only. Batches you start from the dashboard run in test mode too.
The switch is saved in a cookie (`dr_mode`) in your browser. It doesn't affect API requests, your API keys or what other members of your team see. The plan meter in the sidebar always shows live usage, because test renders don't count.
## What's kept apart [#whats-kept-apart]
| Resource | How the mode applies |
| --- | --- |
| [Documents](/docs/concepts/documents) | Created in the key's mode, with `test_mode` set. Lists show only the key's mode. |
| [Batches](/docs/guides/batches) | Created in the key's mode, with `test_mode` set. Their documents are in the same mode. |
| [Share links](/docs/concepts/share-links) | Take the mode of their document, shown in `test_mode`. |
| [Webhook endpoints](/docs/guides/webhooks) | Each endpoint has one mode, chosen when it's created and fixed after that. A test endpoint receives only test events, and every event has `test_mode` set. An API key creates endpoints in its own mode and only sees those; the dashboard lists both modes. |
| [Embedded editor sessions](/docs/guides/embedded-editor) | Created in the key's mode, with `test_mode` set. A key can only revoke sessions of its own mode. |
| Request logs | **Developers › Logs** shows the requests of the dashboard's current mode. |
| Usage | Only live renders count toward your plan. |
These are shared between the modes: templates and their published versions, API keys (the list shows both, with a mode badge), embed settings such as allowed origins, team members, billing and workspace settings.
There's one set of templates per workspace. Publishing a new version changes what `latest` renders in both modes, whether you publish in the dashboard, through an embedded editor session created with a test key, or through the MCP server with a test key. To try template changes without touching live renders, pin `version` in your live requests.
A key only ever sees objects of its own mode. Lists leave the other mode out, and an ID from the other mode answers `404`, as if it didn't exist: documents, batches, share links, webhook endpoints and embedded editor sessions alike.
## Go live [#go-live]
### Build with a test key [#build-with-a-test-key]
Create a **Test** key and use it in local development, CI and staging. Choose **Render only** unless the integration also manages webhooks, reads templates or creates editor sessions.
### Test webhooks with a test endpoint [#test-webhooks-with-a-test-endpoint]
Add a webhook endpoint in test mode that points at your staging or development URL. It receives only test events, so it never sees production documents.
### Switch to a live key [#switch-to-a-live-key]
Create a **Live** key with the permission your production service needs and put it in your production environment. Nothing else in your code changes. If you use webhooks, add a live endpoint for your production URL: it has its own signing secret.
### Check the mode where it matters [#check-the-mode-where-it-matters]
Keep live keys out of development and staging. In webhook handlers and anywhere you act on documents by ID, check `test_mode` so test data can't trigger production work, such as emailing an invoice to a customer.
## E-invoices in test mode [#e-invoices-in-test-mode]
[E-invoices](/docs/guides/e-invoicing) render and validate exactly the same way in both modes. A test Factur-X invoice is the same PDF/A-3 with the same embedded XML as a live one, and the EN 16931, XRechnung and Peppol rules are checked just as strictly. That makes test mode a reliable way to check your invoice data before you go live.
Nothing in the PDF or XML marks a test invoice as a test. Treat test invoices as samples, and don't send them to customers or into accounting or e-invoicing networks.
# Variables and schema (/docs/concepts/variables)
> Declare the data a template expects, see the JSON Schema Druckling derives from it, and validate payloads before you render.
Variables are a template's data contract. You declare each field the template reads, with a path and a type. Druckling turns the list into a JSON Schema, validates every render request against it, and returns it from the API so you can validate on your side too.
## How data binds to a template [#how-data-binds-to-a-template]
The `data` you send to [`POST /v1/documents`](/docs/api-reference/documents/create) is a JSON object. Template strings read from it by dotted path:
```json title="data"
{
"invoice": { "number": "INV-2041", "due_date": "2026-11-22" },
"customer": { "name": "Northwind Ltd.", "address": "12 Pier St, Leeds" },
"line_items": [
{ "description": "Brand identity, phase 2", "qty": 1, "rate": 4800, "amount": 4800 },
{ "description": "Design system audit", "qty": 12, "rate": 180, "amount": 2160 }
],
"totals": { "subtotal": 6960, "tax": 556.8, "amount": 7516.8 }
}
```
- `{{customer.name}}` prints `Northwind Ltd.`
- `{{invoice.due_date | date}}` prints `Nov 22, 2026`
- A table that repeats over `line_items` with the row alias `item` prints one row per item, and its cells read the row: `{{item.description}}`, `{{item.qty}}`, `{{item.amount | money}}`
Paths are dot-separated names made of letters, digits and underscores, and a name can't start with a digit. Template strings can't index into a list (`line_items.0.qty` isn't a valid binding); use a table to print list items. The full syntax is on [Template strings](/docs/concepts/template-strings).
## Declaring variables [#declaring-variables]
In the editor, open the **Data** tab in the left panel and click **Add** under **Variables**. Each variable has:
- **Path**: `customer.address` for a field of an object, `line_items` for a list, `line_items[].qty` for a field of every item in that list.
- **Type**: one of the types below.
- **Required**: whether every request must include it.
- **Description**: copied into the JSON Schema, so it documents the field for whoever calls the API.
Parents are implied: declaring `customer.name` makes `customer` an object, and declaring `line_items[].qty` makes `line_items` a list of objects. You can also declare them explicitly, for example to make the list itself required.
Every binding in the template must point to a declared variable. A binding to an undeclared one is a validation error that blocks publishing. Changing a variable's path in the editor also rewrites the bindings that use it.
### Types [#types]
| Type | Use it for | JSON Schema | Notes |
| --- | --- | --- | --- |
| `string` | Text | `{ "type": "string" }` | |
| `number` | Quantities, rates | `{ "type": "number" }` | |
| `integer` | Counts | `{ "type": "integer" }` | `3.5` is rejected. |
| `money` | Amounts | `{ "type": "number" }` | Send a plain number, such as `4800` or `556.8`. |
| `date` | Dates | `{ "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}" }` | Must start with `YYYY-MM-DD`. A time after it is allowed and ignored by the `date` filter. |
| `boolean` | Flags, often for visibility conditions | `{ "type": "boolean" }` | |
| `image` | Image URLs | `{ "type": "string", "format": "uri" }` | Only public https URLs are fetched. See [Images](#images-barcodes-and-qr-codes). |
| `array` | Repeating rows | `{ "type": "array", "items": … }` | Item fields come from the `[]` paths. |
| `object` | Groups of fields | `{ "type": "object", "properties": … }` | |
The type decides what the schema accepts, not how the value prints. `{{totals.amount}}` prints `7516.8`; `{{totals.amount | money}}` prints `$7,516.80`. Formatting is done with [filters](/docs/concepts/template-strings#filters).
### Required and optional fields [#required-and-optional-fields]
- A required field must be present with the right type. An empty string counts as present.
- A required field makes its parents required. If `customer.address` is required and the payload has no `customer`, the error names `customer`; if `customer` is there without `address`, it names `customer.address`.
- A required list must be present but may be empty (`[]`). Required item fields must be present in every item.
- To leave out an optional field, omit the key. `null` isn't accepted for a typed field: `"tax": null` fails with `totals.tax must be number`.
### Lists [#lists]
A list variable feeds a table or a chart. Declare the list and the fields of its items:
```text
line_items array required
line_items[].description string required
line_items[].qty number required
line_items[].rate money required
line_items[].amount money required
```
A list of plain values, such as `["urgent", "fragile"]`, is a list variable without item fields. In a table over it, the row alias is the value itself: with `each` set to `tags` and the alias `tag`, a cell reads `{{tag}}`.
### Images, barcodes and QR codes [#images-barcodes-and-qr-codes]
An image block shows either a fixed URL or the URL in an `image` variable. Druckling fetches it while rendering, with these limits:
- only public `https://` URLs (no IP addresses or local host names), with no redirects,
- PNG, JPEG, GIF, SVG or WebP, up to 5 MB, answering within 4 seconds,
- up to 20 different images per document.
An image that can't be fetched doesn't fail the render: the block prints its placeholder box instead. The schema accepts any URI (`format: "uri"`), so an `http://` or `data:` URL passes validation but prints the placeholder.
A QR / Barcode block's value is a template string, so it binds any string or number variable, for example `{{payment.url}}` or `https://verify.example.com/{{certificate.id}}`. If the value is empty, or the symbology can't encode it (letters in an EAN-13), the code is left out.
## The derived JSON Schema [#the-derived-json-schema]
Druckling derives a [JSON Schema](https://json-schema.org/) (draft-07) from the variable list. This is the complete schema of the `invoice-standard` starter, as [`GET /v1/templates/invoice-standard`](/docs/api-reference/templates/get) returns it in `json_schema`:
```json title="json_schema"
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"invoice": {
"type": "object",
"properties": {
"number": { "type": "string", "description": "Invoice number shown in the header" },
"due_date": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}" }
},
"required": ["number", "due_date"]
},
"customer": {
"type": "object",
"properties": {
"name": { "type": "string" },
"address": { "type": "string" }
},
"required": ["name", "address"]
},
"line_items": {
"type": "array",
"items": {
"type": "object",
"properties": {
"description": { "type": "string" },
"qty": { "type": "number" },
"rate": { "type": "number" },
"amount": { "type": "number" }
},
"required": ["description", "qty", "rate", "amount"]
}
},
"totals": {
"type": "object",
"properties": {
"subtotal": { "type": "number" },
"tax": { "type": "number" },
"amount": { "type": "number" }
},
"required": ["subtotal", "amount"]
},
"payment": {
"type": "object",
"properties": {
"url": { "type": "string" }
}
}
},
"required": ["invoice", "customer", "line_items", "totals"]
}
```
A few things follow from it:
- **Extra fields are allowed.** The schema doesn't set `additionalProperties: false`, so keys the template doesn't declare pass validation and are ignored by the layout.
- **No type coercion.** `"qty": "12"` fails with `line_items.0.qty must be number`. Send numbers as JSON numbers and booleans as `true` or `false`.
- **Dates are checked for shape only.** `"22.11.2026"` fails, but `"2026-02-31"` passes; see the warning under [the `date` filter](/docs/concepts/template-strings#date).
- **The schema follows the published version.** It changes only when you publish, and the template page's **Schema** tab shows the same schema.
In a template with e-invoicing on, `invoice` is the canonical EN 16931 invoice: its schema replaces whatever the template declares under `invoice`, and the schema carries an extra `x-druckling-einvoice` keyword. Druckling also checks the EN 16931 business rules on every render. See [E-invoicing](/docs/guides/e-invoicing).
## Sample data [#sample-data]
Every template stores an example payload. The editor preview, **Test PDF**, the preview on the template page and the code samples on its **API** tab use it, and the API returns it as `sample_data`.
To change it, open the editor's **Data** tab and edit the JSON under **Sample data**. The panel tells you whether it matches the template's schema; click **Apply** to save it to the draft. **Generate** replaces it with placeholder values derived from the variables, such as names, amounts and dates.
Publishing requires the sample data to match the schema and to render, so a published template always comes with a payload that works. `sample_data` from the API comes from the latest published version (or the draft, before the first publish).
Sample data is stored with the template and anyone with a **Full access** API key for the workspace can read it. Use realistic but made-up values.
## Validation on every render [#validation-on-every-render]
Druckling validates `data` against the schema of the version it renders, before anything is rendered. The same check runs for each item of a [batch](/docs/guides/batches), where one invalid item stops the whole batch.
An invalid payload fails with 422. `data.code` is `schema_validation_failed`, `data.field` is the first field to fix, and `data.errors` lists every problem, with fields that are missing first:
```json title="422 Unprocessable Content"
{
"defined": false,
"code": "UNPROCESSABLE_CONTENT",
"status": 422,
"message": "Required field customer.address was missing from the request payload",
"data": {
"code": "schema_validation_failed",
"field": "customer.address",
"documentId": "pdf_8Qw2kLm3nP0aB1cD",
"errors": [
{ "field": "customer.address", "message": "missing required field customer.address" },
{ "field": "invoice.due_date", "message": "invoice.due_date must be a date like 2026-11-22" },
{ "field": "line_items.0.qty", "message": "line_items.0.qty must be number" }
]
}
}
```
`field` is a dotted path with zero-based list indexes: `line_items.0.qty` is `qty` in the first item. The rejected request is still recorded as a `failed` document (`documentId`), so it shows up under **Documents** with its request body, but it doesn't count toward your plan.
The SDKs raise a `ValidationError` (`ValidationException` in PHP) that carries the same `field` and `errors`. For the full error format, see [Errors](/docs/concepts/errors#validation-errors).
### Size limits [#size-limits]
These limits apply to the payload when it renders, after schema validation:
| Limit | Value | Error |
| --- | --- | --- |
| Payload size | 1,000,000 bytes of JSON | `payload_too_large` (413) |
| Items in one list | 10,000 | `payload_too_large` (413) |
| Nesting depth | 32 levels | `validation_failed` (422) |
For an asynchronous render the request itself succeeds, and the document then fails with that error code. Page limits depend on your plan; see [Plans and limits](/docs/concepts/plans-and-limits#payload-and-render-limits).
## Validate before you call the API [#validate-before-you-call-the-api]
You can check payloads in your own code with the template's schema, for example in a form or before queueing work. Fetch the schema once and cache it: it only changes when you publish, and `latest_version` tells you when that happened. Fetching it needs a **Full access** key.
```ts tab="TypeScript"
import Ajv from "ajv";
import addFormats from "ajv-formats";
import Druckling from "@druckling/sdk";
const druckling = new Druckling();
const template = await druckling.templates.get("invoice-standard");
// strict: false lets Ajv accept Druckling's x-druckling-einvoice keyword on e-invoice templates.
const ajv = new Ajv({ allErrors: true, strict: false });
addFormats(ajv);
const validate = ajv.compile(template.json_schema);
export function problems(data: unknown): { field: string; message: string }[] {
if (validate(data)) return [];
return (validate.errors ?? []).map((error) => {
const base = error.instancePath.slice(1).replaceAll("/", ".");
const field = error.keyword === "required" ? [base, error.params.missingProperty].filter(Boolean).join(".") : base;
return { field, message: error.message ?? "is invalid" };
});
}
console.log(problems({ invoice: { number: "INV-2042", due_date: "2026-12-01" } }));
// [ { field: "customer", ... }, { field: "line_items", ... }, { field: "totals", ... } ]
```
```python tab="Python"
from jsonschema import Draft7Validator
from druckling import Druckling
client = Druckling()
template = client.templates.get("invoice-standard")
validator = Draft7Validator(template.json_schema)
def problems(data):
found = []
for error in validator.iter_errors(data):
field = ".".join(str(part) for part in error.absolute_path)
if error.validator == "required":
missing = error.message.split("'")[1]
field = f"{field}.{missing}" if field else missing
found.append({"field": field, "message": error.message})
return found
print(problems({"invoice": {"number": "INV-2042", "due_date": "2026-12-01"}}))
```
Both produce the same dotted `field` paths as the API. The TypeScript example needs `npm install ajv ajv-formats`, the Python one `pip install jsonschema` (which doesn't check `format: "uri"` unless you pass a format checker).
Client-side validation is a convenience, not a replacement for the server's check: Druckling always validates again, and the e-invoice business rules only run on the server. If you pin a `version`, validate against the schema you fetched while that version was the latest, since the API returns the latest version's schema.
Bind and format the values you declared.
Every error code and how to handle it.
# Accessible PDFs (/docs/guides/accessible-pdfs)
> Render tagged PDF/UA-1 documents and PDF/A archives, and fix what the accessibility checks report before you publish.
Every PDF Druckling renders is tagged: it carries a structure tree that screen readers and other assistive technology can follow. On top of that, a template can claim a PDF standard. PDF/UA-1 makes the document formally accessible, PDF/A makes it fit for long-term archiving, and PDF/A-3a combines archiving with accessibility.
This guide explains the standards, what Druckling takes care of, what you have to provide, and how to check the result.
## Choose a PDF standard [#choose-a-pdf-standard]
The PDF standard is a template setting. In the editor, select the **Document** tab in the right-hand panel and pick a **PDF standard** under **Output**. It applies to every PDF rendered from the published version; there's no API parameter for it, and a pinned version keeps the standard it was published with.
| Setting | What it means | Editor checks |
| --- | --- | --- |
| **Standard PDF** | A tagged PDF without a conformance claim. The default | Nothing extra |
| **PDF/A-2b (archival)** | PDF/A-2, level b, for long-term archiving. No embedded files | Nothing extra |
| **PDF/A-3b (archival + attachments)** | PDF/A-3, level b. Allows embedded files such as e-invoice XML | Nothing extra |
| **PDF/A-3a (archival + attachments, accessible)** | PDF/A-3, level a: archiving plus accessibility requirements | Alt text on images |
| **PDF/UA-1 (accessible)** | PDF/UA-1 (ISO 14289-1), the standard for accessible PDF | Document title, alt text on images, heading order |
A PDF claims one standard, so PDF/UA-1 can't be combined with a PDF/A level. If you need an accessible document that is also an archive, or an accessible [Factur-X or ZUGFeRD e-invoice](/docs/guides/e-invoicing), use PDF/A-3a. Factur-X templates only offer PDF/A-3b and PDF/A-3a, because the invoice XML has to be embedded in a PDF/A-3.
The European Accessibility Act has applied since 28 June 2025 to many products and services sold to consumers in the EU. If documents such as tickets, contracts or statements are part of a service it covers, PDF/UA-1 is the established way to make them accessible.
## What Druckling does for you [#what-druckling-does-for-you]
These apply to every render, whatever standard you choose, unless noted:
- **Tagged structure.** Text blocks, headings, tables and images are tagged in the PDF's structure tree. The reading order is the order of the blocks in the template, top to bottom, and inside a columns block one column after the other.
- **Headings.** Heading blocks become tagged headings of their level (1 to 3), which also gives PDF viewers a document outline.
- **Table headers.** A table's header row is tagged as table headers, so each cell can be read with its column name. With **Repeat header row** on (the default), the header row repeats on every page.
- **Headers and footers.** Blocks in the page header and footer are marked as artifacts, so screen readers don't read the running header and page numbers on every page.
- **Decorative images.** Images marked **Decorative** are artifacts too, and need no alt text.
- **Codes.** QR codes and barcodes get alt text automatically: the kind of code followed by its value, for example `QR code: https://verify.example.com/CERT-8812`. When the value is printed below the code, or spans several lines (like a GiroCode payment QR), the alt text is just the kind, such as `QR code` or `EAN-13 barcode`.
- **Title.** The **Title** under **Document** › **Metadata** is written to the PDF's metadata. In PDF/UA-1 documents, PDF viewers show it in the title bar instead of the file name. A template without a title gets `Document`.
- **Language.** The PDF declares the language it was rendered in, so screen readers pronounce the text correctly. It's the template's default language, or the `language` of the render; see [Multi-language templates](/docs/guides/languages).
## What you provide [#what-you-provide]
The standard can only require what the template supplies. For PDF/UA-1:
- **A document title.** Set **Document** › **Metadata** › **Title**, for example `Invoice`. In a multi-language template, translate it like any other text.
- **Alt text for images.** Select the image block and fill in **Alt text** with what the image conveys, for example `Logo of Acme Studio`. If the image is only decoration, switch on **Decorative** instead. Placeholders without an image source don't need either. Alt text is plain text: bindings like `{{customer.name}}` aren't filled in.
- **Real headings in order.** Use heading blocks for section titles rather than bold text. Start with a level 1 heading and don't skip levels (1, 2, 3, not 1, 3).
- **Headings that are never empty.** A heading that is only a binding, such as `{{invoice.number}}`, is empty when the value is missing. Make the variable required, or add a fallback with the `default` filter, for example `{{invoice.number | default:Invoice}}`. A required variable can still be sent as an empty string, which the `default` filter also covers.
- **A description for charts.** Charts have no alt text setting. Their title and labels are text, but the bars and lines aren't described, so state what the chart shows in a text block next to it.
PDF/A-3a only requires the alt text (or the **Decorative** switch) on images.
## Checks in the editor [#checks-in-the-editor]
While you edit a template with PDF/UA-1 or PDF/A-3a, the editor checks it and lists the problems in the status menu above the canvas, marking the blocks they belong to. Only body blocks are checked; header and footer blocks are artifacts.
| Message | Standard | Fix |
| --- | --- | --- |
| PDF/UA needs a document title (Document settings → Title) | PDF/UA-1 | Fill in **Document** › **Metadata** › **Title** |
| PDF/UA: add alt text to this image, or mark it decorative | PDF/UA-1 | Fill in **Alt text** or switch on **Decorative** |
| PDF/A-3a: add alt text to this image, or mark it decorative | PDF/A-3a | Same |
| PDF/UA: the first heading must be level 1, not 2 | PDF/UA-1 | Change the first heading to level 1 |
| PDF/UA: heading levels can't skip from 1 to 3 | PDF/UA-1 | Use level 2, or add a level 2 heading in between |
| PDF/UA: headings can't be empty | PDF/UA-1 | Give the heading text |
These are errors: the template can't be published until they're fixed. One more check is a warning, because it depends on the data:
```text
PDF/UA rejects empty headings: make the variable required or add a | default
```
In a multi-language template, the checks run for every language, since a translation can leave a heading or an alt text empty. Problems in another language are prefixed with its name, for example `German: PDF/UA: add alt text to this image, or mark it decorative`.
When you publish, Druckling also exports the template once with its sample data in the chosen standard. If the export fails, publishing fails with the reason, and nothing changes for your API calls.
### When data breaks a rule [#when-data-breaks-a-rule]
The checks look at the template; the data arrives later. If a render produces something the standard forbids, for example a heading whose only binding is empty in this payload, the render fails with `render_failed`. A synchronous request answers 422:
```json
{
"defined": false,
"code": "UNPROCESSABLE_CONTENT",
"status": 422,
"message": "PDF/UA-1 error: heading title could not be determined",
"data": {
"code": "render_failed",
"field": null,
"diagnostics": [
{ "severity": "error", "message": "PDF/UA-1 error: heading title could not be determined", "file": "other" }
]
}
}
```
The document is recorded as `failed` with this error, which is also what an async render ends with. Fix the data, or make the template robust with required variables and `default` filters.
## PNG output [#png-output]
[PNG output](/docs/guides/png-output) has no PDF standard: an image can't be tagged or claim conformance. You can still render a page of a PDF/UA-1 template as a PNG; the document's timeline in the dashboard notes that the standard applies to PDF output only.
## Verify the output [#verify-the-output]
Druckling enforces what the export requires, but no tool can judge whether alt text is meaningful or the reading order makes sense. Before relying on a template:
1. Render a few documents with a [test key](/docs/concepts/test-mode), using realistic data, including long values and missing optional fields.
2. Check the files with a validator such as veraPDF, which tests PDF/A and PDF/UA conformance, or an accessibility checker such as PAC.
3. Read a sample with a screen reader, such as NVDA on Windows or VoiceOver on macOS, and listen for the reading order, headings and image descriptions.
Render one template in several languages, with the right PDF language.
Factur-X and ZUGFeRD invoices as PDF/A-3b or PDF/A-3a.
# Batches (/docs/guides/batches)
> Render one template for up to 1,000 payloads in a single request and download every file as one ZIP.
A batch renders one published template for many payloads: a month of invoices, certificates for a whole course, tickets for an event. You send up to 1,000 items in one request. Druckling checks all of them, renders each one as a regular document, and zips the results when the last one finishes.
Use a batch when you have the data for many documents at once and want them as one download. To render documents one at a time as they're needed, call [`POST /v1/documents`](/docs/api-reference/documents/create) instead.
## How a batch works [#how-a-batch-works]
1. **Validation.** Every item's `data` is checked against the template's JSON Schema. If any item is invalid, the whole batch is rejected and nothing is stored or counted.
2. **Queued.** Each item becomes an [asynchronous document](/docs/concepts/documents) whose `batch` is set to its batch ID and position. All items render the same template version, even if you publish a new one while the batch runs.
3. **Running.** The documents render in the background.
4. **Finished.** Once no item is pending, Druckling builds a ZIP of every rendered file and sends the `batch.completed` [webhook](#webhooks).
A batch's `status` moves through these values:
| Status | Meaning |
| --- | --- |
| `queued` | Accepted; the item renders haven't been queued yet. |
| `running` | Items are rendering. |
| `completed` | No item is pending and at least one rendered. `zip_url` is set. Some items may still have failed. |
| `failed` | No item rendered, or Druckling couldn't queue the renders or build the ZIP. `error` says which. |
| `canceled` | You [canceled](#cancel-a-batch) the batch. There's no ZIP. |
`counts` tracks the items: `total`, `pending` (queued or rendering), `rendered`, `failed` and `canceled`. Rendered documents whose files have since expired still count as `rendered`.
## Start a batch [#start-a-batch]
Send the template slug and an `items` array to [`POST /v1/batches`](/docs/api-reference/batches/create). Each item has a `data` payload, plus an optional `filename` and `language`. This file renders two invoices from the `invoice-standard` starter template:
```json title="batch.json"
{
"template": "invoice-standard",
"filename_pattern": "invoice-{{invoice.number}}.pdf",
"items": [
{
"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 }
}
},
{
"data": {
"invoice": { "number": "INV-2042", "due_date": "2026-11-29" },
"customer": { "name": "Fabrikam Inc.", "address": "4 Harbour Rd, Bristol" },
"line_items": [{ "description": "Workshop facilitation", "qty": 2, "rate": 640, "amount": 1280 }],
"totals": { "subtotal": 1280, "tax": 102.4, "amount": 1382.4 }
}
}
]
}
```
The [TypeScript, Python and PHP SDKs](/docs/sdks) don't wrap the batch endpoints yet. Call them over plain HTTP, as below.
```bash tab="cURL"
curl https://druckling-nine.vercel.app/v1/batches \
-H "Authorization: Bearer $DRUCKLING_API_KEY" \
-H "Content-Type: application/json" \
-d @batch.json
```
```ts tab="TypeScript"
import { readFile } from "node:fs/promises";
const response = await fetch("https://druckling-nine.vercel.app/v1/batches", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.DRUCKLING_API_KEY}`,
"Content-Type": "application/json",
},
body: await readFile("batch.json", "utf8"),
});
const batch = await response.json();
if (!response.ok) throw new Error(`${response.status}: ${batch.message}`);
console.log(batch.id, batch.status);
```
```python tab="Python"
import json
import os
import httpx
with open("batch.json") as f:
body = json.load(f)
response = httpx.post(
"https://druckling-nine.vercel.app/v1/batches",
headers={"Authorization": f"Bearer {os.environ['DRUCKLING_API_KEY']}"},
json=body,
timeout=60,
)
batch = response.json()
if response.status_code != 202:
raise RuntimeError(f"{response.status_code}: {batch['message']}")
print(batch["id"], batch["status"])
```
```php tab="PHP"
true,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . getenv('DRUCKLING_API_KEY'),
'Content-Type: application/json',
],
CURLOPT_POSTFIELDS => file_get_contents('batch.json'),
CURLOPT_RETURNTRANSFER => true,
]);
$batch = json_decode(curl_exec($ch), true);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($status !== 202) {
throw new RuntimeException("$status: " . ($batch['message'] ?? 'request failed'));
}
echo $batch['id'], ' ', $batch['status'], PHP_EOL;
```
The answer is `202 Accepted` with the new batch:
```json
{
"id": "bat_3Hk9QmZ1xT7pLw2V",
"object": "batch",
"status": "queued",
"template": "invoice-standard",
"version": 1,
"filename_pattern": "invoice-{{invoice.number}}.pdf",
"counts": { "total": 2, "pending": 2, "rendered": 0, "failed": 0, "canceled": 0 },
"zip_url": null,
"zip_size_bytes": null,
"zip_expires_at": null,
"error": null,
"test_mode": true,
"created_at": "2026-10-27T09:38:02.114Z",
"finished_at": null
}
```
The template needs a published version; otherwise the answer is `404`. `version` defaults to `latest`, which is resolved once, when the batch is created. Pass a version number to pin an older one. Any API key can start a batch, including a **Render only** key.
### Languages [#languages]
For a [multi-language template](/docs/guides/languages), set `language` on the batch to render every item in that language, and `language` on an item to override it for that item. Without either, items render in the template's default language. A language the template doesn't have rejects the whole batch with `422 validation_failed` on `language` or `items.{n}.language`.
## File names [#file-names]
Each item's file name comes from the first of these that is set:
1. The item's own `filename`.
2. `filename_pattern`, rendered with the item's `data`.
3. The default, `{template}-{n}`: the template slug and the item's position, starting at 1.
The default number is zero-padded to the width of the item count, so the files sort correctly: `invoice-standard-1.pdf` to `invoice-standard-9.pdf` for 9 items, `invoice-standard-001.pdf` to `invoice-standard-250.pdf` for 250.
`filename_pattern` uses `{{path}}` bindings into the item's data, such as `invoice-{{invoice.number}}.pdf`. Three filters work: `upper`, `lower`, and `default:"…"` for a fallback when the value is empty. Other filters are ignored and insert the raw value. Bindings only insert strings, numbers and booleans; a missing field, an object or an array inserts nothing. A pattern with an unclosed `{{` is rejected with `422` on `filename_pattern`.
Druckling then cleans up each name:
- Slashes and control characters inside a value become `-`. Any left in the pattern itself or in an item's `filename` are removed, so the ZIP never has folders.
- Spaces, dots, dashes and underscores at either end are trimmed, so a binding that resolved to nothing doesn't leave `invoice-.pdf`. If nothing is left, the default name is used.
- The extension always matches the output: `.pdf`, or `.xml` for [XRechnung and Peppol templates](/docs/guides/e-invoicing). A trailing `.pdf`, `.png` or `.xml` is replaced. Any other extension stays part of the name, so `report.docx` becomes `report.docx.pdf`.
- Names are made unique within the batch, ignoring case: a second `invoice-INV-2041.pdf` becomes `invoice-INV-2041-2.pdf`.
With `"filename_pattern": "invoice-{{invoice.number}}.pdf"`:
| Item | File name |
| --- | --- |
| `invoice.number` is `INV-2041` | `invoice-INV-2041.pdf` |
| A later item whose `invoice.number` is `inv-2041` | `invoice-inv-2041-2.pdf` |
| `invoice.number` is `INV/2042` | `invoice-INV-2042.pdf` |
| No `invoice.number` | `invoice.pdf` |
| The item sets `"filename": "custom.pdf"` | `custom.pdf` |
Names are at most 200 characters. The same name is each document's `filename`.
## Validation comes first [#validation-comes-first]
Druckling validates every item before it stores anything. If one item is invalid, the batch is rejected as a whole, so a run never ships with silent gaps. The answer is `422` and lists the first problem of each invalid item:
```json
{
"defined": false,
"code": "UNPROCESSABLE_CONTENT",
"status": 422,
"message": "Item 1: Required field customer.address was missing from the request payload (2 of 3 items are invalid)",
"data": {
"code": "schema_validation_failed",
"field": "items.1.data.customer.address",
"invalidItems": 2,
"errors": [
{ "index": 1, "field": "customer.address", "message": "Required field customer.address was missing from the request payload" },
{ "index": 2, "field": "invoice.due_date", "message": "Invoice.due_date must be a date like 2026-11-22" }
]
}
}
```
- `data.errors` has one entry per invalid item, in item order, for the first 20 invalid items. `index` is the item's position in `items`, starting at 0, and `field` is the path inside its `data`.
- `data.invalidItems` counts every invalid item, including those past the first 20.
- `data.field` points at the first problem as a full path into the request.
- `data.code` is `schema_validation_failed` for schema errors and `validation_failed` for broken business rules, such as [e-invoice](/docs/guides/e-invoicing) rules.
Nothing was stored or counted, so fix the items and send the whole batch again. To catch problems earlier, fetch the template's schema from [`GET /v1/templates/{slug}`](/docs/api-reference/templates/get) and validate payloads as you build them. See [Variables and JSON Schema](/docs/concepts/variables) and [Errors](/docs/concepts/errors).
## Limits [#limits]
| Limit | Value | When exceeded |
| --- | --- | --- |
| Items per batch | 1 to 1,000 | `400` request validation error |
| Size of `items` as JSON | 4 MB | `413 payload_too_large` |
| `filename_pattern` and each item's `filename` | 200 characters | `400` request validation error |
| Documents left on your plan, in live mode | The whole batch must fit | `429 quota_exceeded` |
A live batch must fit into the documents your plan has left today and this month, after any renders already queued in the workspace. If it doesn't, it's rejected and nothing is stored. Each item that renders counts as one document; failed and canceled items don't count. Test batches are never limited. See [Plans and limits](/docs/concepts/plans-and-limits).
Split larger jobs into several batches. They run independently.
## Track progress [#track-progress]
Poll [`GET /v1/batches/{id}`](/docs/api-reference/batches/get) for the status and live counts, or subscribe to the [`batch.completed` webhook](#webhooks) instead.
```bash
curl https://druckling-nine.vercel.app/v1/batches/bat_3Hk9QmZ1xT7pLw2V \
-H "Authorization: Bearer $DRUCKLING_API_KEY"
```
A loop that waits until the batch has finished:
```ts
async function waitForBatch(id: string) {
for (;;) {
const response = await fetch(`https://druckling-nine.vercel.app/v1/batches/${id}`, {
headers: { Authorization: `Bearer ${process.env.DRUCKLING_API_KEY}` },
});
const batch = await response.json();
if (batch.status !== "queued" && batch.status !== "running") return batch;
await new Promise((resolve) => setTimeout(resolve, 5_000));
}
}
```
[`GET /v1/batches`](/docs/api-reference/batches/list) lists your batches, newest first, optionally filtered by `status`.
### Find the items that failed [#find-the-items-that-failed]
[`GET /v1/batches/{id}/documents`](/docs/api-reference/batches/documents) lists the batch's documents in item order. Filter by `outcome` (`pending`, `rendered`, `failed` or `canceled`) to see only the items that need attention:
```bash
curl "https://druckling-nine.vercel.app/v1/batches/bat_3Hk9QmZ1xT7pLw2V/documents?outcome=failed" \
-H "Authorization: Bearer $DRUCKLING_API_KEY"
```
Each document has `batch.index`, its position in your `items`, and an `error` with a `code`, a `message` and, where it applies, a `field`. Page through long lists with `limit` (up to 100) and `cursor`, passing the `next_cursor` of the previous page.
Documents in list responses have no `url`. To download a single item, fetch it with [`GET /v1/documents/{id}`](/docs/api-reference/documents/get). Batch items also appear in [`GET /v1/documents`](/docs/api-reference/documents/list) like any other document.
To retry failed items, map each `batch.index` back to your own records, fix the data, and send those items as a new batch.
## Download the ZIP [#download-the-zip]
When no item is pending, Druckling builds the ZIP and the batch becomes `completed`, with a signed download link in `zip_url`:
```json
{
"id": "bat_3Hk9QmZ1xT7pLw2V",
"object": "batch",
"status": "completed",
"template": "invoice-standard",
"version": 1,
"filename_pattern": "invoice-{{invoice.number}}.pdf",
"counts": { "total": 2, "pending": 0, "rendered": 2, "failed": 0, "canceled": 0 },
"zip_url": "https://files.example.com/bat_3Hk9QmZ1xT7pLw2V.zip?signature=…",
"zip_size_bytes": 72311,
"zip_expires_at": "2026-11-26T09:38:41.902Z",
"error": null,
"test_mode": true,
"created_at": "2026-10-27T09:38:02.114Z",
"finished_at": "2026-10-27T09:38:41.902Z"
}
```
- The ZIP holds every rendered file, flat and in item order, under the [file names](#file-names) above. Failed and canceled items aren't in it. Files are stored without further compression, since PDFs are compressed already.
- `zip_url` works for up to 7 days, and never past `zip_expires_at`. Every `GET` returns a fresh link, so fetch the batch again rather than storing the URL.
- The ZIP is kept for 30 days after the batch completes (`zip_expires_at`), then deleted; from then on `zip_url` is `null`. Each item's file follows the usual [document retention](/docs/concepts/documents), and batch records are kept for a year.
A batch where nothing rendered ends `failed` without a ZIP, with an error such as `{ "code": "render_failed", "message": "None of the 2 documents rendered" }`. If the ZIP itself can't be built, the batch fails with `zip_failed`, and the rendered documents stay available one by one.
## Cancel a batch [#cancel-a-batch]
[`POST /v1/batches/{id}/cancel`](/docs/api-reference/batches/cancel) stops a `queued` or `running` batch:
```bash
curl -X POST https://druckling-nine.vercel.app/v1/batches/bat_3Hk9QmZ1xT7pLw2V/cancel \
-H "Authorization: Bearer $DRUCKLING_API_KEY"
```
- Items that haven't started rendering become `failed` documents with error code `canceled`, counted in `counts.canceled`.
- Renders that are already running finish, and their documents stay available. `counts` keeps changing until they do.
- A canceled batch never gets a ZIP.
- Once a batch has finished, canceling answers `409 invalid_state`.
## Webhooks [#webhooks]
Subscribe a [webhook endpoint](/docs/guides/webhooks) to `batch.completed` to hear when a batch finishes instead of polling. It's sent once per batch, when the batch becomes `completed`, `failed` or `canceled`. `data` is the batch, including `zip_url`:
```json
{
"id": "evt_5Rn2XqK8wT1mZp4L",
"object": "event",
"type": "batch.completed",
"created_at": "2026-10-27T09:38:41.902Z",
"test_mode": true,
"data": {
"id": "bat_3Hk9QmZ1xT7pLw2V",
"object": "batch",
"status": "completed",
"template": "invoice-standard",
"version": 1,
"filename_pattern": "invoice-{{invoice.number}}.pdf",
"counts": { "total": 2, "pending": 0, "rendered": 2, "failed": 0, "canceled": 0 },
"zip_url": "https://files.example.com/bat_3Hk9QmZ1xT7pLw2V.zip?signature=…",
"zip_size_bytes": 72311,
"zip_expires_at": "2026-11-26T09:38:41.902Z",
"error": null,
"test_mode": true,
"created_at": "2026-10-27T09:38:02.114Z",
"finished_at": "2026-10-27T09:38:41.902Z"
}
}
```
Batch items are ordinary documents, so they also send `document.rendered` and `document.failed` events, with `data.batch` set, and later `document.expired`. A 1,000-item batch can send over a thousand document events. If you only care about the run as a whole, subscribe that endpoint to `batch.completed` alone. Canceled items, and items that never started rendering, don't send `document.failed`; `batch.completed` covers them.
## Run a batch from the dashboard [#run-a-batch-from-the-dashboard]
You can start the same batch from a spreadsheet, without code, under **Automate › Batches**. Batches started through the API show up there too.
### Choose the template [#choose-the-template]
Click **New batch** and pick a published template. Dashboard batches render its latest published version. If the template has several languages, pick the one to render every file in.
### Upload your data [#upload-your-data]
Drop a CSV or JSON file with up to 1,000 rows. The file can be up to 10 MB, and the data built from it up to 4 MB. **Sample CSV for this template** downloads a CSV with one column per variable and the template's sample data as its only row, a good starting point.
Optionally enter a file name pattern, such as `invoice-{{invoice.number}}.pdf`.
### Map columns [#map-columns]
For a CSV, match each column to a template variable, to **File name**, or to **Don't use**. Each variable takes one column. Required variables are marked with `*`, and Druckling warns when one has no column.
### Check and start [#check-and-start]
Druckling validates every row against the template's schema and shows how many are ready and which need fixing, by line number. Fix the file and upload it again, or choose to skip the rows that need fixing and render the rest. In live mode, this step also shows how many documents your plan has left.
The batch runs in the mode the dashboard is in, test or live. Its details show **Dashboard** where API batches show the key's name.
### CSV format [#csv-format]
```csv title="invoices.csv"
invoice.number,invoice.due_date,customer.name,customer.address,line_items,totals.subtotal,totals.tax,totals.amount,File name
INV-2041,2026-11-22,Northwind Ltd.,"12 Pier St, Leeds","[{""description"":""Design system audit"",""qty"":12,""rate"":180,""amount"":2160}]",2160,172.8,2332.8,northwind-2041.pdf
INV-2042,2026-11-29,Fabrikam Inc.,"4 Harbour Rd, Bristol","[{""description"":""Workshop facilitation"",""qty"":2,""rate"":640,""amount"":1280}]",1280,102.4,1382.4,
```
- **Header row.** The first row names the columns, and the separator is detected from it: comma, semicolon or tab. Quoted cells, doubled quotes (`""`), line breaks inside quotes and a UTF-8 byte order mark are all fine; blank lines are skipped.
- **Nested fields.** Headers are dotted variable paths, such as `customer.name`, and build nested objects. Druckling maps a header that matches a path exactly, matches it ignoring case and punctuation (`Customer Name` → `customer.name`), or matches its last segment when that's unambiguous (`address` → `customer.address`). A column named `filename`, `file`, `File name`, `PDF name` or `Dateiname` maps to **File name**. Other columns start as **Don't use**, and you can change any mapping.
- **File names.** A **File name** cell sets that row's name. Rows where it's empty, like the second row above, fall back to the pattern or the default name.
- **Lists.** An array variable, such as `line_items`, is one column holding JSON, as in the example.
- **Types.** Cells are converted to the type the template's schema expects. Numbers accept one decimal separator, `.` or `,`, and spaces between digit groups: `1 234,5` becomes `1234.5`, but `1,234.50` and `1.234,50` stay text and fail validation. `true`, `yes`, `y`, `1` and `false`, `no`, `n`, `0` become booleans, ignoring case. Date variables need dates like `2026-11-22`. A cell that doesn't convert stays text, so validation can point at it.
- **Empty cells** are left out of the payload, so an empty required field fails validation.
A CSV can't set a language per row. For that, upload JSON.
### JSON format [#json-format]
Upload a plain array of payloads, or the same body you'd send to the API, including `items[].filename`, `items[].language`, `filename_pattern` and `language`:
```json title="invoices.json"
[
{
"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 }
}
]
```
## Test mode [#test-mode]
A batch started with an `dr_test_…` key, or from the dashboard in test mode, is a test batch. Its `test_mode` is `true`, it never counts toward your plan, and it only shows up in test mode. Its webhooks go to test endpoints only. See [Test mode](/docs/concepts/test-mode).
# E-invoicing (/docs/guides/e-invoicing)
> Render EN 16931 e-invoices from one invoice payload, as ZUGFeRD and Factur-X PDFs or as XRechnung and Peppol BIS XML.
Druckling produces EN 16931 e-invoices from the same API call that renders any other document. You send the invoice data in `data.invoice`. Druckling computes the line totals, the VAT breakdown and the amount due, checks the business rules, and returns either a PDF/A-3 with the XML embedded or the XML on its own. The template decides which.
This guide covers choosing a format, setting up a template, the invoice payload field by field, what Druckling calculates for you, and how rule violations come back.
## Choose a format [#choose-a-format]
An e-invoice template has one output format. All three are built from the same `invoice` payload, so you can switch a template between them without changing your integration's data.
| Format | What you get | XML syntax | Use it for |
| --- | --- | --- | --- |
| Factur-X 1.0 / ZUGFeRD 2.x | A PDF/A-3 people can read, with the invoice XML embedded as `factur-x.xml` | UN/CEFACT CII D16B | B2B invoices in Germany (ZUGFeRD) and France (Factur-X), where the buyer accepts a hybrid PDF |
| XRechnung 3.0 | The XML on its own | UBL 2.1 (default) or UN/CEFACT CII D16B | German public-sector buyers, who identify themselves with a Leitweg-ID |
| Peppol BIS Billing 3.0 | The XML on its own | UBL 2.1 | Exchange over the Peppol network (Belgium, the Netherlands, the Nordics and more) |
Each format writes its specification identifier (BT-24) into the XML, and the document resource reports it back:
| Format | `einvoice.profile` | `einvoice.customization_id` (BT-24) | Business process (BT-23) |
| --- | --- | --- | --- |
| Factur-X / ZUGFeRD | `EN 16931` | `urn:cen.eu:en16931:2017` | Not written |
| XRechnung | `XRechnung 3.0` | `urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0` | `urn:fdc:peppol.eu:2017:poacc:billing:01:1.0` |
| Peppol BIS | `Peppol BIS Billing 3.0` | `urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0` | `urn:fdc:peppol.eu:2017:poacc:billing:01:1.0` |
Factur-X and ZUGFeRD invoices are always produced at the EN 16931 profile (called COMFORT in older ZUGFeRD versions). The MINIMUM, BASIC WL, BASIC and EXTENDED profiles aren't available.
Druckling generates the invoice file and returns a download link. It doesn't transmit invoices. To send a Peppol BIS invoice over the Peppol network, hand the XML to your Peppol access point; for French e-invoicing platforms or German public-sector portals, upload it the way they require.
## Set up an e-invoice template [#set-up-an-e-invoice-template]
### Start from a starter or an existing template [#start-from-a-starter-or-an-existing-template]
The quickest start is a starter: in the dashboard, go to **Templates** › **New template** and pick **Rechnung (ZUGFeRD)** (German, with the §14 UStG details and a GiroCode payment QR) or **Facture (Factur-X)** (French, with the mandatory mentions as invoice notes). Both come with the invoice variables, a layout with a VAT breakdown, PDF/A-3b and a sample invoice that passes the rules.
To turn an existing template into an e-invoice, open it with **Open editor**, select the **Document** tab in the right-hand panel and, under **Output**, switch on **E-invoice (EN 16931)**.
### Choose the e-invoice format [#choose-the-e-invoice-format]
Under **Output** › **E-invoice format**, choose **Factur-X / ZUGFeRD (PDF)**, **XRechnung (XML)** or **Peppol BIS Billing 3.0 (XML)**. For XRechnung, also pick a **Syntax**: UBL 2.1 or UN/CEFACT CII. Both are valid XRechnung.
Turning e-invoicing on, or changing the format, sets up what the format needs:
- It declares the canonical `invoice.*` variables, including the amounts Druckling computes.
- For Factur-X, it sets **PDF standard** to PDF/A-3b if the template had something else. Factur-X only allows PDF/A-3b or PDF/A-3a, the PDF/A parts that permit embedded files. Choose PDF/A-3a for an accessible invoice (see [Accessible PDFs](/docs/guides/accessible-pdfs)).
- If the sample data doesn't pass the new format's rules, it's replaced with a sample invoice that does.
XRechnung and Peppol templates render XML only. Their layout is used for the editor preview; the **PDF standard** setting has no effect on them.
### Bind the layout to the invoice [#bind-the-layout-to-the-invoice]
Bind your blocks to `invoice.*` paths, for example `{{invoice.number}}`, `{{invoice.seller.name}}`, a table over `invoice.lines` and another over `invoice.vat_breakdown`. Use the computed amounts (`invoice.totals.grand_total`, `line.net_amount`) instead of calculating totals yourself, so the visible PDF shows exactly the numbers in the XML. Show VAT rates with `{{line.vat_rate | number:0-2}}` to print `19` and `5.5` without trailing zeros.
Variables outside `invoice` work as in any template, for example a `logo_url` or a marketing message. A variable you declare under `invoice.` that isn't part of the invoice model gets a warning in the editor: it's neither validated nor written to the XML.
### Publish [#publish]
Publishing checks the sample invoice against the same rules as an API request, so a template can't go live with a sample that would be rejected. Problems show in the status menu above the canvas while you edit.
## Render an e-invoice [#render-an-e-invoice]
Send the invoice in `data.invoice` to [`POST /v1/documents`](/docs/api-reference/documents/create). This request is valid for a Factur-X template created from the **Rechnung (ZUGFeRD)** starter; replace `rechnung` with your template's slug.
```json title="request.json"
{
"template": "rechnung",
"filename": "RE-2026-0042.pdf",
"data": {
"invoice": {
"number": "RE-2026-0042",
"type_code": "380",
"issue_date": "2026-10-20",
"currency": "EUR",
"order_reference": "PO-7781",
"delivery_date": "2026-10-15",
"seller": {
"name": "Acme Studio GmbH",
"legal_id": "HRB 123456 B",
"legal_info": "Amtsgericht Berlin-Charlottenburg HRB 123456 B · Managing director: Ada Weber",
"vat_id": "DE123456789",
"tax_number": "37/123/45678",
"address": { "line1": "Lindenstraße 12", "postcode": "10969", "city": "Berlin", "country": "DE" },
"electronic_address": "billing@acme-studio.example",
"contact": { "name": "Ada Weber", "phone": "+49 30 1234567", "email": "billing@acme-studio.example" }
},
"buyer": {
"name": "Northwind Handels AG",
"id": "K-1001",
"address": { "line1": "Hafenweg 3", "postcode": "20457", "city": "Hamburg", "country": "DE" },
"electronic_address": "purchasing@northwind.example"
},
"lines": [
{ "id": "1", "name": "Brand identity, phase 2", "quantity": 1, "unit_code": "C62", "net_price": 4800, "vat_category": "S", "vat_rate": 19 },
{ "id": "2", "name": "Design system audit", "quantity": 12, "unit_code": "HUR", "net_price": 180, "vat_category": "S", "vat_rate": 19 },
{ "id": "3", "name": "Book: Typography on the web", "quantity": 2, "unit_code": "H87", "net_price": 39.9, "vat_category": "S", "vat_rate": 7 }
],
"allowances_charges": [
{ "kind": "allowance", "amount": 100, "reason": "Loyalty discount", "reason_code": "95", "vat_category": "S", "vat_rate": 19 }
],
"payment": {
"terms": "Payable within 30 days without deduction.",
"due_date": "2026-11-19",
"reference": "RE-2026-0042",
"means_code": "58",
"iban": "DE02120300000000202051",
"bic": "BYLADEM1001",
"account_name": "Acme Studio GmbH"
}
}
}
}
```
```bash tab="cURL"
curl https://druckling-nine.vercel.app/v1/documents \
-H "Authorization: Bearer $DRUCKLING_API_KEY" \
-H "Content-Type: application/json" \
--data @request.json
```
```ts tab="TypeScript"
import { readFile } from "node:fs/promises";
import Druckling from "@druckling/sdk";
const druckling = new Druckling(); // reads DRUCKLING_API_KEY
const { data } = JSON.parse(await readFile("request.json", "utf8"));
const document = await druckling.documents.create({ template: "rechnung", filename: "RE-2026-0042.pdf", data });
console.log(document.einvoice?.format, document.url); // factur-x https://…
```
```python tab="Python"
import json
from druckling import Druckling
client = Druckling() # reads DRUCKLING_API_KEY
with open("request.json", encoding="utf-8") as f:
data = json.load(f)["data"]
document = client.documents.create(template="rechnung", filename="RE-2026-0042.pdf", data=data)
print(document.einvoice.format, document.url) # factur-x https://…
```
```php tab="PHP"
documents->create(template: 'rechnung', data: $data, filename: 'RE-2026-0042.pdf');
echo $document->einvoice->format, ' ', $document->url; // factur-x https://…
```
The response is a [document](/docs/concepts/documents) with an `einvoice` object:
```json
{
"id": "pdf_8Qw2kLm3nP0aB1cD",
"object": "document",
"status": "rendered",
"template": "rechnung",
"version": 1,
"filename": "RE-2026-0042.pdf",
"format": "pdf",
"content_type": "application/pdf",
"image": null,
"pages": 1,
"size_bytes": 48211,
"url": "https://…",
"expires_at": "2026-11-19T09:14:03.000Z",
"error": null,
"einvoice": {
"format": "factur-x",
"syntax": "cii",
"profile": "EN 16931",
"customization_id": "urn:cen.eu:en16931:2017",
"attachment": "factur-x.xml"
},
"batch": null,
"language": "de",
"test_mode": true,
"created_at": "2026-10-20T09:14:02.000Z"
}
```
The PDF is a PDF/A-3 with `factur-x.xml` attached (relationship `Alternative`, MIME type `text/xml`) and the Factur-X XMP metadata that readers look for: document type `INVOICE`, version `1.0`, conformance level `EN 16931`.
The payload is validated before anything is rendered or queued. With `async: true` a valid invoice comes back with status `queued`, but an invalid one still fails right away with a 422, just like a synchronous request.
## The invoice payload [#the-invoice-payload]
`data.invoice` is an EN 16931 invoice in snake_case. Amounts are decimal numbers in the invoice currency, dates are `YYYY-MM-DD` strings and codes are strings, even when they look like numbers (`"380"`, `"58"`).
The JSON Schema returned by [`GET /v1/templates/{slug}`](/docs/api-reference/templates/get) describes the same object, with each field's business term (BT) in its description. Fields you send that aren't part of the model are accepted, but they aren't validated and never reach the XML.
The tables list required fields as EN 16931 requires them. XRechnung and Peppol make more fields mandatory; those appear under [Business rules](#business-rules) and in the required column as "XRechnung" or "Peppol".
### Invoice [#invoice]
| Field | Type | Required | BT | Description |
| --- | --- | --- | --- | --- |
| `number` | string | Yes | BT-1 | Invoice number |
| `type_code` | string | No | BT-3 | `380` invoice (default), `381` credit note, `384` corrected invoice, `389` self-billed invoice, `326` partial invoice, `875` partial construction invoice, `876` partial final construction invoice, `877` final construction invoice |
| `issue_date` | date | Yes | BT-2 | Issue date |
| `currency` | string | Yes | BT-5 | ISO 4217 code in capitals, e.g. `EUR` |
| `buyer_reference` | string | XRechnung | BT-10 | Buyer reference. For German public buyers, their Leitweg-ID |
| `order_reference` | string | No | BT-13 | Purchase order reference |
| `preceding_invoice` | string | No | BT-25 | Invoice a credit note or correction refers to |
| `preceding_invoice_date` | date | No | BT-26 | Issue date of the preceding invoice |
| `delivery_date` | date | No | BT-72 | Date of supply or service |
| `billing_period.start` | date | No | BT-73 | Service period start |
| `billing_period.end` | date | No | BT-74 | Service period end |
| `notes` | array | No | BG-1 | Invoice notes, see [Notes and delivery](#notes-and-delivery) |
| `seller` | object | Yes | | See [Seller and buyer](#seller-and-buyer) |
| `buyer` | object | Yes | | See [Seller and buyer](#seller-and-buyer) |
| `delivery` | object | No | | Deliver-to party, see [Notes and delivery](#notes-and-delivery) |
| `lines` | array | Yes | BG-25 | Invoice lines, see [Lines](#lines) |
| `allowances_charges` | array | No | BG-20, BG-21 | Document-level allowances and charges, see [Allowances and charges](#allowances-and-charges) |
| `vat_exemptions` | array | No | | Exemption reasons per VAT category, see [VAT categories](#vat-categories) |
| `payment` | object | No | | Payment terms and instructions, see [Payment](#payment) |
| `prepaid_amount` | number | No | BT-113 | Amount already paid, at most 2 decimals |
### Seller and buyer [#seller-and-buyer]
`seller` and `buyer` share one shape. Where the business terms differ, the table shows the seller's first.
| Field | Type | Required | BT (seller / buyer) | Description |
| --- | --- | --- | --- | --- |
| `name` | string | Yes | BT-27 / BT-44 | Legal name |
| `trading_name` | string | No | BT-28 / BT-45 | Trading name, if different |
| `id` | string | No | BT-29 / BT-46 | Seller identifier; for the buyer, your customer number |
| `legal_id` | string | No | BT-30 / BT-47 | Legal registration, e.g. `HRB 123456 B` or a SIREN |
| `legal_id_scheme` | string | No | | ISO 6523 scheme of `legal_id`, e.g. `0002` for SIREN, `0208` for a Belgian enterprise number |
| `legal_info` | string | No | BT-33 (seller only) | Additional legal information, e.g. register court and share capital |
| `tax_number` | string | No | BT-32 (seller only) | National tax number (Steuernummer) |
| `vat_id` | string | No | BT-31 / BT-48 | VAT identifier with its country prefix, e.g. `DE123456789` |
| `address` | object | Yes | | See the address table below |
| `electronic_address` | string | XRechnung, Peppol | BT-34 / BT-49 | E-mail address, Leitweg-ID or Peppol participant identifier |
| `electronic_address_scheme` | string | Peppol | | EAS code of `electronic_address`. Default `EM` (e-mail), which Peppol doesn't accept. Common codes: `0204` Leitweg-ID, `9930` German VAT number, `0208` Belgian enterprise number, `0088` GLN |
| `contact.name` | string | XRechnung (seller) | BT-41 / BT-56 | Contact person or department |
| `contact.phone` | string | XRechnung (seller) | BT-42 / BT-57 | Contact phone |
| `contact.email` | string | XRechnung (seller) | BT-43 / BT-58 | Contact e-mail |
The `address` object:
| Field | Type | Required | BT (seller / buyer) | Description |
| --- | --- | --- | --- | --- |
| `line1` | string | No | BT-35 / BT-50 | Street and number |
| `line2` | string | No | BT-36 / BT-51 | Address line 2 |
| `line3` | string | No | BT-162 / BT-163 | Address line 3 |
| `postcode` | string | XRechnung | BT-38 / BT-53 | Post code |
| `city` | string | XRechnung | BT-37 / BT-52 | City |
| `region` | string | No | BT-39 / BT-54 | Region or state |
| `country` | string | Yes | BT-40 / BT-55 | ISO 3166-1 alpha-2 code in capitals, e.g. `DE` |
### Lines [#lines]
Each item of `lines` is one invoice line.
| Field | Type | Required | BT | Description |
| --- | --- | --- | --- | --- |
| `id` | string | No | BT-126 | Line number. Defaults to the line's position (`"1"`, `"2"`, …) |
| `name` | string | Yes | BT-153 | Item name |
| `description` | string | No | BT-154 | Item description |
| `seller_item_id` | string | No | BT-155 | Your item number |
| `note` | string | No | BT-127 | Line note |
| `quantity` | number | Yes | BT-129 | Invoiced quantity |
| `unit_code` | string | Yes | BT-130 | UN/ECE Recommendation 20 unit, 2 or 3 capitals or digits: `C62` one, `H87` piece, `HUR` hour, `DAY` day |
| `net_price` | number | Yes | BT-146 | Net unit price. Can't be negative |
| `price_base_quantity` | number | No | BT-149 | Quantity the price refers to. Default 1, must be positive |
| `vat_category` | string | Yes | BT-151 | VAT category code, see [VAT categories](#vat-categories) |
| `vat_rate` | number | No | BT-152 | VAT rate in percent, e.g. `19` or `5.5`. Unset counts as 0 |
### Allowances and charges [#allowances-and-charges]
Document-level discounts and surcharges go in `allowances_charges`. Each one belongs to a VAT category and rate, and Druckling subtracts or adds it in that group of the VAT breakdown.
| Field | Type | Required | BT (allowance / charge) | Description |
| --- | --- | --- | --- | --- |
| `kind` | string | Yes | | `allowance` or `charge` |
| `amount` | number | Yes | BT-92 / BT-99 | Positive amount, at most 2 decimals |
| `reason` | string | One of the two | BT-97 / BT-104 | Reason text |
| `reason_code` | string | One of the two | BT-98 / BT-105 | Reason code: UNCL 5189 for allowances (e.g. `95` discount), UNCL 7161 for charges (e.g. `FC` freight) |
| `vat_category` | string | Yes | BT-95 / BT-102 | VAT category code |
| `vat_rate` | number | No | BT-96 / BT-103 | VAT rate in percent |
### VAT categories [#vat-categories]
`vat_category` takes a UNCL 5305 code. Some categories need a reason in `vat_exemptions`, an array with one entry per category:
| Field | Type | Required | BT | Description |
| --- | --- | --- | --- | --- |
| `category` | string | Yes | | The VAT category the reason applies to |
| `reason` | string | One of the two | BT-120 | Exemption reason text, printed in the VAT breakdown |
| `code` | string | One of the two | BT-121 | Exemption reason code, e.g. `VATEX-EU-AE` |
| Code | Meaning | Rate | Also needs |
| --- | --- | --- | --- |
| `S` | Standard rate | Above 0 | Seller VAT ID or tax number |
| `Z` | Zero rated | 0 | Seller VAT ID or tax number. No exemption reason |
| `E` | Exempt from VAT | 0 | Seller VAT ID or tax number, exemption reason |
| `AE` | Reverse charge | 0 | Seller VAT ID or tax number, buyer VAT ID (or legal ID), exemption reason |
| `K` | Intra-community supply | 0 | Seller and buyer VAT IDs, a delivery date or billing period, the deliver-to country, exemption reason |
| `G` | Export outside the EU | 0 | Seller VAT ID, exemption reason |
| `O` | Not subject to VAT | None, any rate is ignored | No VAT IDs on either party, exemption reason |
| `L` | Canary Islands (IGIC) | Above 0 | Seller VAT ID or tax number |
| `M` | Ceuta and Melilla (IPSI) | Above 0 | Seller VAT ID or tax number |
### Payment [#payment]
| Field | Type | Required | BT | Description |
| --- | --- | --- | --- | --- |
| `terms` | string | See below | BT-20 | Payment terms |
| `due_date` | date | See below | BT-9 | Due date |
| `reference` | string | No | BT-83 | Remittance information, e.g. the invoice number |
| `means_code` | string | XRechnung | BT-81 | UNCL 4461 payment means: `58` SEPA credit transfer, `59` SEPA direct debit, `30` credit transfer, `49` direct debit, `48` bank card, `10` cash, `57` standing agreement, `ZZZ` mutually defined |
| `iban` | string | For `30` and `58` | BT-84 | Payee IBAN |
| `bic` | string | No | BT-86 | Payee BIC |
| `account_name` | string | No | BT-85 | Payee account name |
| `mandate_id` | string | For `59` in XRechnung, `49` and `59` in Peppol | BT-89 | Direct debit mandate reference |
| `creditor_id` | string | For `59` in XRechnung | BT-90 | Your SEPA creditor identifier |
| `debited_account` | string | For `59` in XRechnung | BT-91 | The buyer's IBAN to debit |
When an amount is due, the invoice needs a `due_date` or `terms` (BR-CO-25).
### Notes and delivery [#notes-and-delivery]
| Field | Type | Required | BT | Description |
| --- | --- | --- | --- | --- |
| `notes[].text` | string | Yes | BT-22 | Note text |
| `notes[].subject_code` | string | No | BT-21 | UNTDID 4451 subject, e.g. `AAB`, `PMT`, `PMD`, `REG`, `AAI` |
| `delivery.name` | string | No | BT-70 | Deliver-to party name |
| `delivery.address.line1` | string | No | BT-75 | Deliver-to street |
| `delivery.address.postcode` | string | No | BT-78 | Deliver-to post code |
| `delivery.address.city` | string | No | BT-77 | Deliver-to city |
| `delivery.address.country` | string | No | BT-80 | Deliver-to country code. The deliver-to address is only written to the XML when it's set |
## What Druckling computes [#what-druckling-computes]
Don't send totals. Druckling calculates them from the lines, allowances and charges, writes them to the XML and makes them available to the template, so the PDF and the XML always agree.
| Computed field | BT | How it's calculated |
| --- | --- | --- |
| `lines[].net_amount` | BT-131 | `quantity` × `net_price` ÷ `price_base_quantity`, rounded to cents |
| `allowances_charges[].signed_amount` | | The amount, negative for allowances (handy in a table) |
| `vat_breakdown[]` | BG-23 | One entry per VAT category and rate: `category` (BT-118), `rate` (BT-119), `basis` (BT-116), `tax` (BT-117), `exemption_reason` (BT-120) |
| `totals.line_total` | BT-106 | Sum of line net amounts |
| `totals.allowance_total` | BT-107 | Sum of allowances |
| `totals.charge_total` | BT-108 | Sum of charges |
| `totals.tax_basis_total` | BT-109 | Line total − allowances + charges |
| `totals.tax_total` | BT-110 | Sum of the breakdown's VAT amounts |
| `totals.grand_total` | BT-112 | Total without VAT + total VAT |
| `totals.prepaid` | BT-113 | `prepaid_amount`, or 0 |
| `totals.due_payable` | BT-115 | Grand total − prepaid |
How the arithmetic works:
- **VAT is calculated once per group.** Each VAT breakdown entry adds the line net amounts of its category and rate, subtracts its allowances and adds its charges; the VAT is that basis × rate, rounded once. Druckling never rounds VAT per line, as EN 16931 requires.
- **Exact decimals.** Amounts are calculated in fixed-point decimals, not floating point, and rounded half away from zero to cents. Three items at `0.335` make `1.01`, not `1.00`.
- **Precision of your inputs.** Quantities and prices can have more than two decimals. Allowance and charge amounts and `prepaid_amount` can have at most two (BR-DEC-01, BR-DEC-16).
- **Anything you send is overwritten.** If your payload contains `totals`, `vat_breakdown` or `lines[].net_amount`, Druckling replaces them with its own values.
For the request above, the template sees:
```json
{
"totals": {
"line_total": 7039.8,
"allowance_total": 100,
"charge_total": 0,
"tax_basis_total": 6939.8,
"tax_total": 1308.99,
"grand_total": 8248.79,
"prepaid": 0,
"due_payable": 8248.79
},
"vat_breakdown": [
{ "category": "S", "rate": 7, "basis": 79.8, "tax": 5.59, "exemption_reason": "" },
{ "category": "S", "rate": 19, "basis": 6860, "tax": 1303.4, "exemption_reason": "" }
]
}
```
The loyalty discount of 100 sits in the 19% group, so its basis is 4,800 + 2,160 − 100 = 6,860. In an e-invoice template, the `money` filter uses the invoice's `currency`, not the template's currency setting.
## Business rules [#business-rules]
Before rendering, Druckling checks the payload in two steps:
1. **Shape**, against the template's JSON Schema: required fields, types, date and code formats. A problem answers 422 with code `schema_validation_failed`.
2. **Business rules**, the cross-field rules of EN 16931 and of the format's CIUS. A broken rule answers 422 with code `validation_failed`. The message ends with the rule's ID in parentheses and `field` points at the offending value.
Both come back in the same [error format](/docs/concepts/errors). `data.errors` lists every problem found, each with its `field` and `message`, and `rule` for business rules. The failed attempt is recorded as a `failed` document; `data.documentId` is its ID.
For example, an XRechnung invoice without a buyer reference:
```json
{
"defined": false,
"code": "UNPROCESSABLE_CONTENT",
"status": 422,
"message": "The buyer reference is required (for public buyers: their Leitweg-ID) (BR-DE-15)",
"data": {
"code": "validation_failed",
"field": "invoice.buyer_reference",
"documentId": "pdf_3Hk9QmZ1xT7pLw2V",
"errors": [
{
"field": "invoice.buyer_reference",
"message": "The buyer reference is required (for public buyers: their Leitweg-ID) (BR-DE-15)",
"rule": "BR-DE-15"
}
]
}
}
```
A reverse-charge line without the buyer's VAT ID and exemption reason reports both rules:
```json
"errors": [
{ "field": "invoice.buyer.vat_id", "message": "Reverse charge needs the buyer's VAT identifier (BR-AE-02)", "rule": "BR-AE-02" },
{ "field": "invoice.lines.0.vat_category", "message": "VAT category AE needs an exemption reason or code in vat_exemptions (BR-AE-10)", "rule": "BR-AE-10" }
]
```
The SDKs raise these as validation errors, with every rule in `errors`:
```ts tab="TypeScript"
import Druckling, { ValidationError } from "@druckling/sdk";
const druckling = new Druckling();
try {
await druckling.documents.create({ template: "xrechnung", data: { invoice } });
} catch (error) {
if (!(error instanceof ValidationError)) throw error;
for (const problem of error.errors) {
console.log(problem.rule, problem.field, problem.message);
}
}
```
```python tab="Python"
from druckling import Druckling, ValidationError
client = Druckling()
try:
client.documents.create(template="xrechnung", data={"invoice": invoice})
except ValidationError as error:
for problem in error.errors:
print(problem.rule, problem.field, problem.message)
```
```php tab="PHP"
use Druckling\Exception\ValidationException;
use Druckling\Druckling;
$druckling = new Druckling();
try {
$druckling->documents->create(template: 'xrechnung', data: ['invoice' => $invoice]);
} catch (ValidationException $e) {
foreach ($e->errors as $problem) {
echo $problem->rule, ' ', $problem->field, ' ', $problem->message, PHP_EOL;
}
}
```
The editor runs the same checks on your sample data and shows broken rules in the preview, for example `E-invoice: A seller contact point (name or department) is required (BR-DE-5)`.
Druckling checks the rules that depend on your data. Rules about the XML's structure are guaranteed by the generator. This isn't a full run of the official schematron: if a recipient requires certified validation, check a sample with the validator they name, such as the KoSIT validator for XRechnung or the Peppol BIS validation artifacts.
### EN 16931 rules [#en-16931-rules]
These apply to every format.
| Rule | Field | Checks |
| --- | --- | --- |
| `BR-DATE` | any date | The date exists in the calendar (`2026-02-30` fails). A Druckling check, not an EN 16931 rule ID |
| `BR-29` | `billing_period.end` | The billing period doesn't end before it starts |
| `BR-CO-26` | `seller.vat_id` | The seller has an `id`, `legal_id` or `vat_id` |
| `BR-CO-09` | `seller.vat_id`, `buyer.vat_id` | VAT IDs start with a two-letter country prefix |
| `BR-27` | `lines.n.net_price` | The net price isn't negative |
| `BR-DEC` | `lines.n.price_base_quantity` | The base quantity is positive. A Druckling check |
| `BR-DEC-01` | `allowances_charges.n.amount` | Positive, at most 2 decimals |
| `BR-33`, `BR-38` | `allowances_charges.n.reason` | Each allowance (BR-33) or charge (BR-38) has a `reason` or `reason_code` |
| `BR-DEC-16` | `prepaid_amount` | At most 2 decimals |
| `BR-S-05`, `BR-L-05`, `BR-M-05` | `….vat_rate` | Categories `S`, `L` and `M` have a rate above 0 |
| `BR-Z-05`, `BR-E-05`, `BR-AE-05`, `BR-IC-05`, `BR-G-05` | `….vat_rate` | Categories `Z`, `E`, `AE`, `K` and `G` have rate 0 |
| `BR-S-02`, `BR-Z-02`, `BR-E-02`, `BR-L-02`, `BR-M-02` | `seller.vat_id` | These categories need the seller's VAT ID or tax number |
| `BR-AE-02` | `seller.vat_id`, `buyer.vat_id` | Reverse charge needs the seller's VAT ID or tax number and the buyer's VAT ID or legal ID |
| `BR-IC-02` | `seller.vat_id`, `buyer.vat_id` | Intra-community supply needs both VAT IDs |
| `BR-IC-11` | `delivery_date` | Intra-community supply needs a delivery date or billing period start |
| `BR-IC-12` | `delivery.address.country` | Intra-community supply needs the deliver-to country |
| `BR-G-02` | `seller.vat_id` | Export needs the seller's VAT ID |
| `BR-O-02` | `seller.vat_id` or `buyer.vat_id` | An invoice not subject to VAT carries no VAT IDs |
| `BR-E-10`, `BR-AE-10`, `BR-IC-10`, `BR-G-10`, `BR-O-10` | `lines.n.vat_category` | Categories `E`, `AE`, `K`, `G` and `O` have a reason or code in `vat_exemptions` |
| `BR-S-10`, `BR-Z-10` | `vat_exemptions.n` | Categories `S` and `Z` have no exemption reason |
| `BR-CO-25` | `payment.due_date` | An amount due has a due date or payment terms |
| `BR-61` | `payment.iban` | Credit transfers (`30`, `58`) have the payee's IBAN |
### XRechnung rules [#xrechnung-rules]
XRechnung adds the German CIUS rules (BR-DE) and the electronic addresses it made mandatory.
| Rule | Field | Checks |
| --- | --- | --- |
| `PEPPOL-EN16931-R020` | `seller.electronic_address` | The seller has an electronic address |
| `PEPPOL-EN16931-R010` | `buyer.electronic_address` | The buyer has an electronic address |
| `BR-CL-25` | `….electronic_address_scheme` | The scheme is on the CEF EAS code list (`EM` when unset is fine) |
| `BR-DE-1` | `payment.means_code` | Payment instructions are given: set the payment means code |
| `BR-DE-3`, `BR-DE-4` | `seller.address.city`, `seller.address.postcode` | The seller's city and post code |
| `BR-DE-5`, `BR-DE-6`, `BR-DE-7` | `seller.contact.name`, `.phone`, `.email` | A seller contact with name, phone and e-mail |
| `BR-DE-8`, `BR-DE-9` | `buyer.address.city`, `buyer.address.postcode` | The buyer's city and post code |
| `BR-DE-10`, `BR-DE-11` | `delivery.address.city`, `.postcode` | A deliver-to address with a country also has a city and post code |
| `BR-DE-15` | `buyer_reference` | A buyer reference (the Leitweg-ID for public buyers) |
| `BR-DE-18` | `payment.terms` | Skonto lines read like `#SKONTO#TAGE=14#PROZENT=2.00#`, in capitals, each followed by a line break |
| `BR-DE-23-b` | `payment.mandate_id` or `payment.debited_account` | A credit transfer (`30`, `58`) carries no direct debit details |
| `BR-DE-24-a` | `payment.means_code` | Card payments (`48`) aren't supported: use `30`, `58` or `59` |
| `BR-DE-25-a` | `payment.mandate_id` | A SEPA direct debit (`59`) has the mandate reference |
| `BR-DE-25-b` | `payment.iban` | A SEPA direct debit has no payee IBAN: send the buyer's IBAN as `debited_account` |
| `BR-DE-30` | `payment.creditor_id` | A SEPA direct debit has your creditor identifier |
| `BR-DE-31` | `payment.debited_account` | A SEPA direct debit has the IBAN to debit |
### Peppol BIS rules [#peppol-bis-rules]
| Rule | Field | Checks |
| --- | --- | --- |
| `PEPPOL-EN16931-R020`, `PEPPOL-EN16931-R010` | `seller.electronic_address`, `buyer.electronic_address` | Both parties have an electronic address (their Peppol participant ID) |
| `PEPPOL-EN16931-CL008` | `….electronic_address_scheme` | The scheme is set and on the Peppol EAS code list. `EM` (e-mail) isn't |
| `PEPPOL-COMMON-R040` | `….electronic_address`, `….legal_id` | Scheme `0088`: a GLN with a valid GS1 check digit |
| `PEPPOL-COMMON-R041` | same | Scheme `0192`: a 9-digit Norwegian organisation number |
| `PEPPOL-COMMON-R042` | same | Scheme `0184`: a Danish CVR number (8 digits, optionally prefixed `DK`) |
| `PEPPOL-COMMON-R043` | same | Scheme `0208`: a 10-digit Belgian enterprise number with valid check digits |
| `PEPPOL-COMMON-R049` | same | Scheme `0007`: a 10-digit Swedish organisation number |
| `PEPPOL-COMMON-R050` | same | Scheme `0151`: an 11-digit Australian Business Number |
| `PEPPOL-EN16931-R003` | `buyer_reference` | A buyer reference or a purchase order reference |
| `PEPPOL-EN16931-R002` | `notes.1` | At most one note, unless both parties are in Germany |
| `PEPPOL-EN16931-P0100` | `type_code` | The type is part of Peppol BIS Billing: `389` (self-billing) isn't |
| `PEPPOL-EN16931-P0112` | `type_code` | `326` and `384` only between parties in Germany |
| `PEPPOL-EN16931-R061` | `payment.mandate_id` | Direct debits (`49`, `59`) have the mandate reference |
When both the seller and the buyer are in Germany (`address.country` is `DE` for both), a Peppol invoice also has to pass the German rules from the XRechnung table, reported with Peppol's IDs: `DE-R-001` for BR-DE-1, `DE-R-015` for BR-DE-15, `DE-R-025-1` and `DE-R-025-2` for BR-DE-25-a and -b, and so on.
## Format notes [#format-notes]
### Factur-X and ZUGFeRD [#factur-x-and-zugferd]
- The only extra requirement is the PDF standard: PDF/A-3b (the starters' default) or PDF/A-3a. PDF/UA-1 can't be used, because a PDF claims one standard and Factur-X needs PDF/A-3.
- Electronic addresses are optional. Without a scheme, an address is written with scheme `EM` (e-mail).
- The template's layout is yours, but the numbers come from the payload: bind to the computed fields so the page and `factur-x.xml` agree.
### XRechnung [#xrechnung]
A complete XRechnung invoice for a German federal authority. The buyer reference and the buyer's electronic address both carry the Leitweg-ID, with EAS scheme `0204`:
```json title="xrechnung-request.json"
{
"template": "xrechnung",
"data": {
"invoice": {
"number": "RE-2026-0043",
"issue_date": "2026-10-20",
"currency": "EUR",
"buyer_reference": "04011000-12345-03",
"order_reference": "BE-2026-118",
"delivery_date": "2026-10-15",
"seller": {
"name": "Acme Studio GmbH",
"legal_id": "HRB 123456 B",
"vat_id": "DE123456789",
"address": { "line1": "Lindenstraße 12", "postcode": "10969", "city": "Berlin", "country": "DE" },
"electronic_address": "billing@acme-studio.example",
"contact": { "name": "Ada Weber", "phone": "+49 30 1234567", "email": "billing@acme-studio.example" }
},
"buyer": {
"name": "Bundesamt für Beispielwesen",
"address": { "line1": "Musterallee 1", "postcode": "53113", "city": "Bonn", "country": "DE" },
"electronic_address": "04011000-12345-03",
"electronic_address_scheme": "0204"
},
"lines": [
{ "name": "Brand identity, phase 2", "quantity": 1, "unit_code": "C62", "net_price": 4800, "vat_category": "S", "vat_rate": 19 },
{ "name": "Design system audit", "quantity": 12, "unit_code": "HUR", "net_price": 180, "vat_category": "S", "vat_rate": 19 }
],
"payment": {
"terms": "Payable within 30 days.\n#SKONTO#TAGE=10#PROZENT=2.00#\n",
"due_date": "2026-11-19",
"reference": "RE-2026-0043",
"means_code": "58",
"iban": "DE02120300000000202051",
"bic": "BYLADEM1001",
"account_name": "Acme Studio GmbH"
}
}
}
}
```
The document comes back as XML:
```json
{
"format": "xml",
"content_type": "application/xml",
"filename": "xrechnung-8Qw2kLm3.xml",
"pages": null,
"einvoice": {
"format": "xrechnung",
"syntax": "ubl",
"profile": "XRechnung 3.0",
"customization_id": "urn:cen.eu:en16931:2017#compliant#urn:xeinkauf.de:kosit:xrechnung_3.0",
"attachment": null
}
}
```
Things to know:
- `buyer_reference` (BT-10) is mandatory. Public buyers give you their Leitweg-ID for it; for other buyers, use the reference they ask for.
- Both parties need an `electronic_address`. An e-mail address works with the default scheme `EM`; a Leitweg-ID uses `0204`, a German VAT number `9930`.
- The seller needs a full contact (name, phone, e-mail) and both parties a city and post code.
- `payment.means_code` is mandatory. For a cash discount (Skonto), add a line like `#SKONTO#TAGE=10#PROZENT=2.00#` to `payment.terms`, followed by a line break. To give the base amount, write `#SKONTO#TAGE=10#PROZENT=2.00#BASISBETRAG=500.00#`.
- For a SEPA direct debit, use `means_code: "59"` with `mandate_id`, `creditor_id` and `debited_account`, and leave `iban` out.
### Peppol BIS Billing [#peppol-bis-billing]
A Belgian B2B invoice. Both parties are addressed by their enterprise number (EAS `0208`), and the same number is their legal ID:
```json title="peppol-request.json"
{
"template": "peppol-invoice",
"data": {
"invoice": {
"number": "FAC-2026-0158",
"issue_date": "2026-10-20",
"currency": "EUR",
"buyer_reference": "MKT-2026",
"order_reference": "PO-4471",
"delivery_date": "2026-10-16",
"seller": {
"name": "Studio Noord BV",
"legal_id": "0123456749",
"legal_id_scheme": "0208",
"vat_id": "BE0123456749",
"address": { "line1": "Kortrijksesteenweg 112", "postcode": "9000", "city": "Gent", "country": "BE" },
"electronic_address": "0123456749",
"electronic_address_scheme": "0208",
"contact": { "name": "Lotte Peeters", "phone": "+32 9 123 45 67", "email": "invoices@studionoord.example" }
},
"buyer": {
"name": "Brasserie Lambiek NV",
"legal_id": "0987654394",
"legal_id_scheme": "0208",
"vat_id": "BE0987654394",
"address": { "line1": "Grote Markt 7", "postcode": "1000", "city": "Brussel", "country": "BE" },
"electronic_address": "0987654394",
"electronic_address_scheme": "0208"
},
"lines": [
{ "name": "House style design", "quantity": 1, "unit_code": "C62", "net_price": 2400, "vat_category": "S", "vat_rate": 21 },
{ "name": "Workshop", "quantity": 2, "unit_code": "DAY", "net_price": 750, "vat_category": "S", "vat_rate": 21 },
{ "name": "Printed menu cards", "quantity": 250, "unit_code": "H87", "net_price": 1.84, "vat_category": "S", "vat_rate": 21 }
],
"payment": {
"terms": "Payment within 30 days of the invoice date.",
"due_date": "2026-11-19",
"reference": "FAC-2026-0158",
"means_code": "58",
"iban": "BE68539007547034",
"bic": "GKCCBEBB",
"account_name": "Studio Noord BV"
}
}
}
}
```
Things to know:
- Both parties need a Peppol participant ID: `electronic_address` plus its `electronic_address_scheme`. E-mail addresses can't be Peppol endpoints.
- For the schemes in the Peppol table (`0088`, `0192`, `0184`, `0208`, `0007`, `0151`), Druckling checks the identifier's format and check digits, in `electronic_address` and in `legal_id`.
- Send a `buyer_reference` or an `order_reference`.
- Merge notes into one, unless both parties are in Germany.
- Self-billed invoices (`389`) aren't part of Peppol BIS Billing.
### Credit notes [#credit-notes]
Set `type_code` to `381` and reference the invoice you're crediting. Amounts stay positive: the type code makes it a credit. In UBL syntax (XRechnung, Peppol) Druckling writes a `CreditNote` document instead of an `Invoice`.
```json
{
"invoice": {
"number": "CN-2026-0007",
"type_code": "381",
"issue_date": "2026-10-27",
"preceding_invoice": "RE-2026-0043",
"preceding_invoice_date": "2026-10-20",
"lines": [
{ "name": "Credit: design system audit (2 hours)", "quantity": 2, "unit_code": "HUR", "net_price": 180, "vat_category": "S", "vat_rate": 19 }
],
"payment": { "terms": "We'll refund the amount to your account.", "due_date": "2026-11-03", "means_code": "58", "iban": "DE02120300000000202051" }
}
}
```
The other fields (`currency`, `buyer_reference`, `seller`, `buyer`) are the same as on the original invoice. The starters' layouts switch their heading to Gutschrift or Avoir when `type_code` is `381`.
### Reverse charge and exempt supplies [#reverse-charge-and-exempt-supplies]
Categories other than `S`, `Z`, `L` and `M` need an exemption reason. For a German seller invoicing a Belgian business customer under reverse charge:
```json
{
"buyer": {
"name": "Studio Noord BV",
"vat_id": "BE0123456749",
"address": { "line1": "Kortrijksesteenweg 112", "postcode": "9000", "city": "Gent", "country": "BE" }
},
"lines": [
{ "name": "Design system audit", "quantity": 12, "unit_code": "HUR", "net_price": 180, "vat_category": "AE", "vat_rate": 0 }
],
"vat_exemptions": [
{ "category": "AE", "reason": "Reverse charge: VAT is due from the recipient", "code": "VATEX-EU-AE" }
]
}
```
The reason appears in the VAT breakdown as `exemption_reason`, so a template can print it next to the 0% line.
## Output formats per template [#output-formats-per-template]
The `format` parameter of [`POST /v1/documents`](/docs/api-reference/documents/create) defaults to what the template produces. Asking for another format answers 422 `validation_failed` on `format`; Druckling never switches silently.
| Template | Default | Accepted | Rejected |
| --- | --- | --- | --- |
| No e-invoicing | `pdf` | `pdf`, `png` | `xml` |
| Factur-X / ZUGFeRD | `pdf` | `pdf` | `png`, `xml` (the XML lives inside the PDF) |
| XRechnung or Peppol BIS | `xml` | `xml` | `pdf`, `png` |
To send a readable PDF along with an XRechnung or Peppol invoice, render it from a second e-invoice template set to Factur-X, with the same data. Its PDF shows the same computed totals.
## XML documents [#xml-documents]
XRechnung and Peppol documents have `format: "xml"`, `content_type: "application/xml"`, `pages: null`, a file name ending in `.xml` and `einvoice.attachment: null`. Everything else works as for PDFs: download the file from `url`, poll or subscribe to [webhooks](/docs/guides/webhooks) for async renders, and create [share links](/docs/concepts/share-links). Each XML document counts as one document toward your [plan](/docs/concepts/plans-and-limits) in live mode.
Rendering an XML e-invoice doesn't run the typesetter: the XML is generated from the payload and the layout plays no part. The `language` parameter is still validated and recorded on the document, but it doesn't change the XML. In a Factur-X PDF, `language` changes the visible pages only; the embedded XML is the same in every language. See [Multi-language templates](/docs/guides/languages).
## Batches of e-invoices [#batches-of-e-invoices]
[Batches](/docs/guides/batches) work with e-invoice templates. Every item's invoice is checked against the schema and the business rules before anything renders. If any item fails, nothing is rendered and the 422 names the first problem, for example `field: "items.3.data.invoice.buyer_reference"`, with `data.errors` listing the first invalid items.
XRechnung and Peppol batches produce XML files: file names end in `.xml` (a `.pdf` in `filename_pattern` or an item's `filename` becomes `.xml`), and the batch ZIP contains the XML files.
```bash
curl https://druckling-nine.vercel.app/v1/batches \
-H "Authorization: Bearer $DRUCKLING_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"template": "xrechnung",
"filename_pattern": "{{invoice.number}}.xml",
"items": [
{ "data": { "invoice": { "number": "RE-2026-0043", "…": "…" } } },
{ "data": { "invoice": { "number": "RE-2026-0044", "…": "…" } } }
]
}'
```
## Test before you go live [#test-before-you-go-live]
Render with a `dr_test_…` key while you build your integration: [test-mode](/docs/concepts/test-mode) documents go through exactly the same validation and generation and don't count toward your quota. Check a few generated files with the validators your recipients use before switching to a live key.
Combine Factur-X with PDF/A-3a for an accessible e-invoice.
Render a month of invoices in one request.
The error format and every error code.
# Embedded editor (/docs/guides/embedded-editor)
> Let your users edit a Druckling template inside your own product, in a white-label editor that you frame on your pages.
The embedded editor puts Druckling's template editor inside your product, so your users can change their own invoice, certificate or ticket layout without a Druckling account. Your backend creates a short-lived session for one template, your frontend shows it in an iframe, and the editor tells your page what happens over `postMessage`.
## How it works [#how-it-works]
1. **Once:** allow the origins of your app in **Settings › Embed**.
2. **When a user opens the editor:** your backend creates a session with `POST /v1/embed_sessions` and passes the returned `url` to that user's browser.
3. **In the browser:** your page mounts the `url` in an iframe, with `@druckling/embed` or a plain `