# API Reference

> For AI agents: a documentation index is available at https://makespdf.com/llms.txt — every docs page also has a markdown twin (append .md to the page URL), including this one: https://makespdf.com/docs/api.md

Generate beautiful, PDF/A-2A + PDF/UA-1 compliant documents from structured data.
Designed for AI agents and API clients — no templates to learn, no design
decisions to make.

> **For AI agents:** before hand-writing requests, read the canonical
> [skill file](https://makespdf.com/skills/pdf-template-author.md) — it teaches the compact
> DSL used by `/api/v1/preview` and `/api/v1/render`, plus document recipes
> (invoice, receipt, CV, report). Also useful:
> [/llms.txt](https://makespdf.com/llms.txt) (machine-readable site manifest) and
> [/ai](https://makespdf.com/ai) (per-tool setup for Claude Code, Cursor, ChatGPT,
> etc.).

## Choosing an endpoint

Five ways to get from data to a PDF. Pick by **what you have**, not by what
sounds most powerful:

```text
What do you have?
│
├── Markdown content, want a PDF with default styling?
│     → POST /api/v1/md               (about a second, no AI)
│
├── An Obsidian / JSON Canvas board (.canvas)?
│     → POST /api/v1/canvas           (about a second, no AI)
│
├── Structured data for a common doc type
│   (invoice, receipt, quote, cv, statement, certificate, letter)?
│     → POST /api/v1/render { type, data }   (~20s, AI auto-generates template)
│       Fastest path to a working PDF — no DSL to write.
│
└── Custom layout, brand-specific, or data doesn't fit a standard type?
      → POST /api/v1/preview { dsl, data }   (about a second, deterministic)
        Full control. Write the DSL taught in the skill file.
```

**Rule of thumb:** `/md` for docs, `/render` for quick starts on standard
types, `/preview` when you want pixel control. Reuse a generated template via
`POST /api/v1/templates` + `/render` with `templateId` if you need repeatable,
fast renders with consistent design.

## Overview

The main endpoints. Every render runs the same deterministic pipeline; none of
them call an AI model.

| Endpoint | Purpose | Speed | Rate limit |
| --- | --- | --- | --- |
| `POST /api/v1/preview` | Render inline DSL while authoring (free) | about 1s | 200/hour |
| `POST /api/v1/templates` | Save a DSL template | fast | 100/hour |
| `GET /api/v1/templates` | List library and your templates | fast | 500/hour |
| `GET /api/v1/templates/:id` | Get a single template | fast | 500/hour |
| `POST /api/v1/render` | Render a saved template or inline DSL | about 1s | 10,000/hour |
| `POST /api/v1/md` | Markdown to PDF | about 1s | 10,000/hour |
| `POST /api/v1/canvas` | JSON Canvas board to PDF | about 1s | 10,000/hour |

**Recommended workflow:** Iterate on a template with `/preview`, save it once,
then render it repeatedly with different data through `/render`.

## Authentication

Endpoints require authentication by default. Two methods are supported:

1. **Bearer token** — pass your API key in the `Authorization` header:

```http
Authorization: Bearer your-api-key
```

2. **Session cookie** — if you're logged in to the web app, your session cookie is
   accepted automatically.
3. **Wallet payment (x402)** — pay per call in USDC on Base mainnet with no
   account at all. POST with no auth, get a `402` advertising the price, sign an
   EIP-3009 authorization, and resend with a `PAYMENT-SIGNATURE` header. Retrying
   the same signature within 5 minutes is idempotent.

| Wallet-payable endpoint | Price |
| --- | --- |
| `POST /api/v1/markdown` | $0.01 per render |
| `POST /api/v1/render` | $0.02 per render — inline `{ dsl, data }` body only; `templateId` is account-only |
| `POST /api/v1/enhance` | priced per page — read the amount from the 402 challenge |

Use `/api/v1/markdown` rather than `/api/v1/md` as your wallet entry point. They
run the same pipeline at the same price, but `/api/v1/md` also honours the
anonymous promo below, so an unauthenticated call there may return a PDF or a
`401` instead of the `402` you need. `/api/v1/markdown` always issues the
challenge. Full wire format and a worked example live in
[/llms.txt](https://makespdf.com/llms.txt) under §Pay-per-call.

Unauthenticated requests normally receive a `401` response.
[Manage your API keys →](https://makespdf.com/settings/api-keys)

**Carve-outs.** `POST /api/v1/pdf/validate` (the hosted veraPDF utility —
JSON-only, no PDF output), `POST /api/v1/md` (Markdown → PDF, when the
anonymous-renders promo is on) and `POST /api/v1/feedback` (feedback from the
plugins — no PDF, nothing billed) accept unauthenticated requests with stricter
per-IP rate limits. A stale or invalid Bearer token still returns 401 on every
endpoint — we never silently downgrade an authentication attempt.

## Device Authorization (for AI agents & CLIs)

If your agent or CLI needs to authenticate without pre-configured API keys, use
the [OAuth Device Authorization
Grant](https://datatracker.ietf.org/doc/html/rfc8628) flow. The agent opens the
user's browser, the user approves, and the agent receives a persistent API key.

1. **Request a device code** — `POST /api/v1/device/code` with an optional
   `client_name`. Returns `device_code`, `user_code`,
   `verification_uri_complete`, `expires_in`, and `interval`.
2. **Open the browser** — direct the user to `verification_uri_complete` (code
   pre-filled) or display the `user_code` for manual entry.
3. **Poll for the token** — `POST /api/v1/device/token` with `device_code` every
   5 seconds.
4. **Handle responses** — `authorization_pending` (keep polling), `slow_down`
   (increase interval by 5s), `access_denied` (abort), `expired_token`
   (restart).
5. **On success** — the response includes an `access_token`. Store it and use as
   `Authorization: Bearer <token>` for all subsequent API calls. The token is a
   persistent API key.

```bash
# 1. Request device code
curl -X POST https://makespdf.com/api/v1/device/code \
  -H "Content-Type: application/json" \
  -d '{"client_name": "My AI Agent"}'

# 2. Open the verification_uri_complete in the user's browser

# 3. Poll for the token
curl -X POST https://makespdf.com/api/v1/device/token \
  -H "Content-Type: application/json" \
  -d '{"device_code": "<device_code from step 1>"}'
```

## Endpoints

**POST /api/v1/templates**

Generate a reusable PDF template via AI. The template is a design tailored to
your data shape, with `{{variable}}` placeholders that can be filled with
different data on each render. Call multiple times with the same input to get
alternative designs.

**Request body**

| Field | Type | Description |
| --- | --- | --- |
| `type` required | string | Document type: "invoice", "receipt", "quote", "cv", "resume", "statement", "certificate", or "letter". |
| `data` required | object | The structured data for your document. The AI designs the template around this shape. Max 50KB. |
| `style` optional | string | Style hint: "modern", "classic", "minimal", "bold", or a freeform description. Max 200 chars. |
| `brand` optional | object | Brand customisation with optional logoUrl, primaryColor, secondaryColor, and fontPreference. |

**Example request**

```http
POST /api/v1/templates
Content-Type: application/json
Authorization: Bearer your-api-key

{
  "type": "invoice",
  "style": "modern",
  "brand": {
    "primaryColor": "#2563eb",
    "logoUrl": "https://example.com/logo.png"
  },
  "data": {
    "company": "Acme Corp",
    "invoiceNumber": "INV-001",
    "date": "2025-03-15",
    "items": [
      { "description": "Web design", "quantity": 1, "unitPrice": 2500 },
      { "description": "Hosting (annual)", "quantity": 1, "unitPrice": 300 }
    ],
    "subtotal": 2800,
    "tax": 280,
    "total": 3080
  }
}
```

**Example response**

```json
201 Created

{
  "templateId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "type": "invoice",
  "style": "modern",
  "model": "claude",
  "version": 1,
  "dataShape": "company,date,invoiceNumber,items[description,quantity,unitPrice],subtotal,tax,total",
  "generationMs": 18420,
  "costUsd": 0.032,
  "createdAt": "2025-03-15T10:30:00.000Z"
}
```

> **Tip:** The `dataShape` field describes the structure of your data. Templates
> work best when re-used with data of the same shape — same keys, same array
> structure.

**GET /api/v1/templates**

List your saved templates, newest first. Only returns templates owned by the
authenticated caller.

**Query parameters**

| Field | Type | Description |
| --- | --- | --- |
| `id` optional | string (UUID) | If provided, returns a single template by ID (including the full content/definition). |
| `type` optional | string | Filter by document type: "invoice", "receipt", "quote", "cv", "statement", "certificate", or "letter". |
| `limit` optional | number | Max results to return. Default 20, max 100. |
| `offset` optional | number | Pagination offset. Default 0. |

**Example: list templates**

```http
 GET /api/v1/templates?type=invoice&limit=5
Authorization: Bearer your-api-key
```

```json
200 OK

{
  "templates": [
    {
      "templateId": "a1b2c3d4-...",
      "type": "invoice",
      "style": "modern",
      "dataShape": "company,date,items[...],total",
      "model": "claude",
      "version": 1,
      "createdAt": "2025-03-15T10:30:00"
    }
  ],
  "total": 1,
  "limit": 5,
  "offset": 0
}
```

**Example: get single template**

```http
 GET /api/v1/templates?id=a1b2c3d4-e5f6-7890-abcd-ef1234567890
Authorization: Bearer your-api-key
```

Returns the full template including the `content` field (the DocumentDefinition
JSON). The list endpoint omits content to keep responses compact.

**POST /api/v1/render**

Render a PDF. Supports two modes depending on the request body:

**Mode 1: Render from template (fast)** — pass a `templateId` from a previously
created template, plus fresh data. No AI call — renders in about a second.

| Field | Type | Description |
| --- | --- | --- |
| `templateId` required | string (UUID) | The ID of a template created via POST /api/v1/templates. |
| `data` required | object | Fresh data to populate the template. Should match the same shape as the original. Max 50KB. |

**Example request**

```http
POST /api/v1/render
Content-Type: application/json
Authorization: Bearer your-api-key

{
  "templateId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "data": {
    "company": "Different Corp",
    "invoiceNumber": "INV-002",
    "date": "2025-03-20",
    "items": [
      { "description": "Consulting", "quantity": 10, "unitPrice": 150 }
    ],
    "subtotal": 1500,
    "tax": 150,
    "total": 1650
  }
}
```

**Mode 2: One-shot render (slow)** — pass a `type` and `data` to generate a
template and render in a single request. Convenient but slower (~20s) and the
template is not saved for reuse.

| Field | Type | Description |
| --- | --- | --- |
| `type` required | string | Document type: "invoice", "receipt", "quote", "cv", "resume", "statement", "certificate", or "letter". |
| `data` required | object | The structured data for your document. Max 50KB. |
| `style` optional | string | Style hint. Max 200 chars. |
| `brand` optional | object | Brand customisation (logoUrl, primaryColor, secondaryColor, fontPreference). |

**Example request**

```http
POST /api/v1/render
Content-Type: application/json
Authorization: Bearer your-api-key

{
  "type": "receipt",
  "data": {
    "store": "Corner Shop",
    "date": "2025-03-15",
    "items": [
      { "name": "Coffee", "quantity": 2, "price": 4.50 },
      { "name": "Croissant", "quantity": 1, "price": 3.00 }
    ],
    "total": 12.00,
    "paymentMethod": "Card ending 4242"
  }
}
```

**Response** — by default, the response is the PDF binary with
`Content-Type: application/pdf`. Metadata is returned in response headers:

| Header | Meaning |
| --- | --- |
| `X-Pages` required | Number of pages in the PDF. |
| `X-Render-Ms` required | Total render time in milliseconds. |
| `X-Model` optional | AI model used (only present for one-shot mode). |
| `X-Rate-Limit-Remaining` required | Remaining requests in the current rate limit window. |

> **JSON metadata:** Send `Accept: application/json` to receive render metadata
> as JSON instead of the PDF binary. Useful for checking page count and timing
> without downloading the file.

**Hybrid e-invoices (Factur-X / ZUGFeRD)** — `/render` (both the `templateId` and
`dsl` body shapes) accepts `options.facturX`. Send your invoice as
CrossIndustryInvoice XML and the PDF comes back as a hybrid e-invoice: PDF/A-3A with
the XML embedded as an associated file and described in the XMP metadata, still
tagged for PDF/UA-1. Without this option the output is unchanged (PDF/A-2A and
PDF/UA-1).

`/preview` and `/preview/validate` check `options.facturX` and return the same 400
errors, but `/preview` does not embed the XML: its PDF stays PDF/A-2A and the
response carries `X-Factur-X: valid; not embedded, use /api/v1/render`. Only
`/render` produces the e-invoice.

| Field | Type | Description |
| --- | --- | --- |
| `options.facturX.xml` required | string | The invoice XML. Well-formed UTF-8, max 1 MB, root element CrossIndustryInvoice in the namespace urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100. A DOCTYPE is refused. |
| `options.facturX.profile` required | string | One of "MINIMUM", "BASIC WL", "BASIC", "EN 16931", "EXTENDED" or "XRECHNUNG". The embedded file is named xrechnung.xml for XRECHNUNG and factur-x.xml otherwise. |
| `options.facturX.relationship` optional | string | "Data", "Alternative" or "Source". Defaults to "Data" for MINIMUM and BASIC WL (which must be Data) and "Alternative" for every other profile. |

**Example request**

```http
POST /api/v1/render
Content-Type: application/json
Authorization: Bearer your-api-key

{
  "templateId": "invoice-classic",
  "data": { "invoiceNumber": "INV-002" },
  "options": {
    "facturX": {
      "xml": "<rsm:CrossIndustryInvoice xmlns:rsm=\"urn:un:unece:uncefact:data:standard:CrossIndustryInvoice:100\" ...>...</rsm:CrossIndustryInvoice>",
      "profile": "EN 16931"
    }
  }
}
```

A malformed or out-of-spec XML payload returns 400 with `details` and a hint; on
`/render` an x402 payer gets that 400 before payment settles. makesPDF does not
check the invoice's business content (EN 16931 or XRechnung rules): you supply
valid XML. Check it with a free validator, such as the KoSIT validator for
XRechnung or the Mustang and FNFE-MPE tools for Factur-X. MINIMUM and BASIC WL are
not valid invoices in Germany. Billing and limits are unchanged.

**POST /api/v1/md**

Convert GitHub Flavored Markdown to PDF. No AI call — pure computation,
typically under 200ms.

**Anonymous usage.** When the promo is on, you can call this endpoint without an
Authorization header. Anonymous limits: 60 requests/hour and 200/day per IP, and
20 pages per render. Anonymous responses carry an `X-MakesPDF-Tip` header
nudging sign-up; rate-limit and page-cap rejections include the same nudge in a
`tip` field. Sign up for higher limits, saved renders, and access to the rest of
the API.

**Request body**

| Field | Type | Description |
| --- | --- | --- |
| `markdown` required | string | GitHub Flavored Markdown content. Max 200KB of text; inline `data:` images are excluded from that budget. Request body max 15MB. A single block (lines with no blank line between them) maxes out at ~8MB — past that the request fails with `413` and code `markdown-block-too-large`. A blank line splits paragraph and image blocks and renders the same content; it cannot split a fenced code block (close the fence and open another), and between table rows it splits one table into two, which renders differently. Markdown shaped so that parsing it would take seconds (thousands of unclosed `[text](` links or unmatched `*` markers in one paragraph, say) is refused before parsing with `400` and code `markdown-too-complex`; the response's `rule` and `hint` name what to change. A document may also hold at most 150,000 lines (`rule: block-count`); that ceiling is reachable only on a canvas text card. |
| `options.pageSize` optional | string | "A3", "A4" (default), "A5", "Letter", or "Legal". |
| `options.fontFamily` optional | string | "Inter" (default) or "NotoSans". |
| `options.fontSize` optional | number | Base font size in points (6–24, default 10). |
| `options.margins` optional | array | [top, right, bottom, left] in points. Default [40, 40, 40, 40]. |
| `options.title` optional | string | PDF document title. Max 200 chars. |
| `options.author` optional | string | PDF document author (/Author). Max 200 chars. |
| `options.subject` optional | string | One-line description of the document (/Subject). Max 200 chars. |
| `options.keywords` optional | string \| string[] | Topic keywords (/Keywords). An array, or one comma-separated string. Max 500 chars. |
| `options.lang` optional | string | Document language (BCP 47) — sets the PDF /Lang and picks the built-in CJK font: "ja", "ko", "zh-Hant", "zh-Hans"… Omit to infer from the text (kana → Japanese, Hangul → Korean, else Simplified Chinese). |
| `options.splitMode` optional | string | "default" keeps headings with their content; "balanced" splits large sections to fill pages. |
| `options.theme` optional | string | "default" (current style) or "github" — GitHub markdown styling with lighter semibold headings, h1/h2 underlines, and GitHub colours. Matches the VS Code Markdown PDF extension. |
| `options.pageNumbers` optional | string | Footer page numbers. "page-n-of-total" → "Page 3 of 12", "n-of-total" → "3 / 12", "n" → "3". Omit for no page numbers. |
| `options.pageNumberPosition` optional | string | Footer alignment when pageNumbers is set: "left", "center", or "right" (default). Ignored without pageNumbers. |

**Example request**

```http
POST /api/v1/md
Content-Type: application/json
Authorization: Bearer your-api-key

{
  "markdown": "# Hello\n\nSome **bold** text.",
  "options": {
    "pageSize": "Letter",
    "fontFamily": "NotoSans"
  }
}
```

**Anonymous example (when promo is on)**

```http
POST /api/v1/md
Content-Type: application/json

{
  "markdown": "# Hello\n\nSome **bold** text."
}
```

> **Layout warnings.** A binary response carries `X-Layout-Warnings` when the
> render succeeded but rendered something degraded: a comma-separated list of
> the distinct warning codes, for example `glyph-missing` (a character no font
> covers — drawn blank) or `page-split-overflow`. Codes only — no counts, no
> codepoints and no document text. The header is absent when the render warned
> about nothing, and `Accept: application/json` gives the full warning list in
> `layoutWarnings`.

**Paying by wallet: `/api/v1/markdown`.** `POST /api/v1/markdown` is the
always-paid twin of this endpoint. Identical pipeline, identical options,
identical price — the only difference is that it never honours the anonymous
promo, so an unauthenticated call always returns a `402` challenge rather than a
PDF or a `401`. That makes it the reliable entry point for wallet-holding
agents, and the one listed in our x402 discovery feeds. A Bearer token works on
either route.

```http
POST /api/v1/markdown
Content-Type: application/json

{
  "markdown": "# Hello\n\nSome **bold** text."
}

# → 402 Payment Required, with the price and payment details in the body.
# Sign an EIP-3009 authorization and resend with:
#   PAYMENT-SIGNATURE: <base64 PaymentPayload>
```

**POST /api/v1/canvas**

Convert a JSON Canvas 1.0 document (an Obsidian `.canvas` board) to PDF. No AI
call — pure computation. Cards render through the same markdown pipeline as
`/md`, so headings, lists, tables, images, Mermaid and graph blocks all work
inside text cards, and card content uses an Obsidian theme by default — the board
looks like Obsidian renders it, not like a GitHub README (see `options.theme`
below). A file card draws its file name as a faint node label above the card;
edges become a tagged vector connector layer.

**Anonymous usage.** When the promo is on, canvas can be called without an
Authorization header, with the same limits as `/md`: 60 requests/hour and
200/day per IP, and 20 pages per render. Canvas is not payable per call — a
`PAYMENT-SIGNATURE` header does not buy access.

**PDF file nodes.** A `.pdf` card imports one page of the source PDF as vector
content — text stays text, contain-fitted and centred in the node rect, tagged as
one `Figure` with *PDF: `<file name>`, page N* as its alt text. The page comes from
the node subpath (`#page=2`), or page 1 for a bare path. A PDF that cannot be
embedded — encrypted, unembedded fonts, CMYK colour, JavaScript, and so on —
renders its placeholder card instead and the response carries a
`canvas-pdf-not-embeddable` warning with the reason; a malformed or out-of-range
page falls back to page 1 with `canvas-pdf-page-out-of-range`. The render never
fails.

**Request body**

| Field | Type | Description |
| --- | --- | --- |
| `canvas` required | object \| string | The JSON Canvas document, or the raw `.canvas` file text. Max 2MB (JSON). Unknown node types are skipped with a warning, never an error. |
| `files` optional | object | Contents for the paths the canvas references, keyed by the exact `file` / `background` string: `{ data: "data:image/png;base64,…" }` for images and PDFs, `{ markdown: "# Note" }` for `.md` notes. Images, PDFs and notes resolve through this map; without it they render as placeholder cards. |
| `options.pageSize` optional | string | Fit the board on a sheet: "A3", "A4", "A5", "Letter", or "Legal" (auto landscape/portrait by board shape). Omit to make the page the board itself. |
| `options.fontFamily` optional | string | "Inter" (default) or "NotoSans". |
| `options.theme` optional | string | Card-content theme: "obsidian" (default) mirrors Obsidian's own reading-view styling — heading sizes, spacing, blockquote bar, code and lists — because a canvas is not a GitHub document. "github" and "default" keep the markdown themes' earlier looks. Card geometry (padding, coloured-card tint) and file-node labels are always Obsidian's. |
| `options.title` / `options.author` / `options.subject` / `options.keywords` optional | string | Document metadata. Same limits as `/md`: 200 chars each, keywords 500. |
| `options.lang` optional | string | Document language (BCP 47) — sets the PDF /Lang and picks the built-in CJK font. |

**Limits:** request body max 25MB (canvas JSON max 2MB), 5,000 nodes and 10,000
edges per board, 1,000,000 characters of text across text nodes and supplied note
markdown, coordinates within ±1e7, 50 diagrams (Mermaid + graph) per board — past
that a diagram renders as its source code block with a `canvas-diagram-limit`
warning — 60 images per board, and 10 PDFs per board with a 5MB cap each. A board
estimated at more than 3s of wall-clock layout work — thousands of inline elements
in one card, one unbreakable run wider than a line, text that spans hundreds of
one-line pages in a short card, or simply too many cards (the estimate charges a
fixed cost per card) — is refused before layout with a `400` and code
`canvas-too-complex` (rule `"layout-work"`, `details` naming the card, and a
`hint` saying what to change: split one huge card, or use fewer cards). Authed
callers are billed 1 credit per 10 pages on success; every failure path deducts
zero.

**Example request**

```http
POST /api/v1/canvas
Content-Type: application/json
Authorization: Bearer your-api-key

{
  "canvas": {
    "nodes": [
      { "id": "n1", "type": "text", "text": "# Hello", "x": 0, "y": 0, "width": 400, "height": 200 }
    ],
    "edges": []
  },
  "options": { "pageSize": "A4", "title": "Board" }
}
```

**Raw .canvas file example** — the `canvas` field also accepts the raw file text,
which clients can send without parsing it first. Reference files (images, notes)
travel separately in `files`.

```http
POST /api/v1/canvas
Content-Type: application/json
Authorization: Bearer your-api-key

{
  "canvas": "<contents of my-board.canvas>",
  "files": {
    "photo.png": { "data": "data:image/png;base64,…" },
    "notes/spec.md": { "markdown": "# Spec\n…" }
  }
}
```

> **JSON metadata:** Send `Accept: application/json` to receive render metadata
> (including `layoutWarnings` for skipped nodes / clipped cards) instead of the
> PDF binary.

**Layout warnings on the binary response.** The PDF response carries
`X-Layout-Warnings` when the board rendered with warnings: a comma-separated
list of the distinct codes, for example `canvas-unsupported-node` (an unknown
node type was skipped) or `canvas-file-missing` (a file card whose file you did
not supply). Codes only — no counts and no board content, so a client that
streams the PDF can still tell the export was degraded. The header is absent
when the board warned about nothing.

**POST /api/v1/feedback**

Send feedback about the service — a problem, an idea, or praise. No PDF is
produced and nothing is billed.

**Authentication is optional.** Anonymous callers are welcome (10/hour and 30/day
per IP); a Bearer token or session cookie records the account with the feedback
(30/hour). A stale or invalid Bearer token still returns 401. This is the
endpoint the VS Code and Obsidian plugins use for their in-editor feedback
prompts.

**Request body**

| Field | Type | Description |
| --- | --- | --- |
| `message` required | string | The feedback itself. 1–4000 characters. |
| `kind` required | string | "problem", "idea", or "praise". |
| `context` optional | object | Fingerprint-only render context the plugins fill in automatically: errorCode, httpStatus, pageCount, inputBytes, pageSize, fontFamily, fontSize, theme. Unknown keys are rejected. |

**Example request**

```http
POST /api/v1/feedback
Content-Type: application/json

{
  "message": "Table columns overflow when a cell is very long.",
  "kind": "problem",
  "context": { "pageCount": 3, "pageSize": "A4", "theme": "github" }
}

# → 200 { "feedbackId": "...", "receivedAt": "..." }
```

**Privacy.** Feedback text is stored and used to improve the product, and is kept
until deleted — see the [privacy policy](https://makespdf.com/legal/privacy). Please don't
paste document content you would not want us to keep.

**POST /api/v1/enhance**

Remediate an existing PDF (alt text, structure tags, accessibility metadata).
Async — submitting returns `202` with a `jobId` in under a second; clients poll
`GET /api/v1/enhance/jobs/:id` until `status` is terminal. We also email you when
the job is ready and surface the PDF on `/settings/renders`.

**Request body**

| Field | Type | Description |
| --- | --- | --- |
| `pdfBase64` required | string | The PDF to remediate, base64-encoded. Max 25MB decoded. |
| `options.mode` optional | string | "in-place" (default and only supported value in v1). "regenerate" / "both" 400 with a pointer to the v1 restriction. |
| `options.title` optional | string | Override the PDF /Title metadata. Max 200 chars. |
| `options.author` optional | string | Set the PDF /Author metadata. Max 200 chars. The source document's value is kept when omitted. |
| `options.subject` optional | string | Set the PDF /Subject metadata. Max 200 chars. The source document's value is kept when omitted. |
| `options.keywords` optional | string | Set the PDF /Keywords metadata, comma-separated. Max 500 chars. The source document's value is kept when omitted. |
| `options.altTextOverrides` optional | array | Per-figure alt-text overrides keyed by (page, mcid). Max 500 entries. Lets you correct vision output without re-paying for vision. |

**Optional headers**

| Header | Description |
| --- | --- |
| `Idempotency-Key` optional | Opaque caller-supplied dedup key. Re-submitting the same key returns the existing jobId without enqueuing a duplicate. Max 200 chars. |

**202 response**

```json
{
  "jobId": "f8e1…",
  "status": "queued",
  "statusUrl": "/api/v1/enhance/jobs/f8e1…",
  "estimatedSeconds": 240
}
```

**Polling recipe** — start at a 2-second cadence and back off to 8 seconds after
the first 30 seconds. Give up after 30 minutes. The status response carries
`phase` and a `progress: { current, total }` object you can render as a real
progress bar.

```bash
# 1. Submit
curl -s -X POST https://makespdf.com/api/v1/enhance \
  -H "Authorization: Bearer $MAKESPDF_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: my-unique-key-001" \
  -d "{\"pdfBase64\":\"$(base64 < input.pdf)\"}"
# → { "jobId": "f8e1…", "status": "queued",
#     "statusUrl": "/api/v1/enhance/jobs/f8e1…", "estimatedSeconds": 240 }

# 2. Poll until terminal
while :; do
  resp=$(curl -s -H "Authorization: Bearer $MAKESPDF_API_KEY" \
    "https://makespdf.com/api/v1/enhance/jobs/f8e1…")
  status=$(echo "$resp" | jq -r .status)
  echo "$resp" | jq -c '{status, phase, progress}'
  case "$status" in
    succeeded|partial|failed|cancelled) break ;;
  esac
  sleep 2
done

# 3. Download on success
artifactId=$(echo "$resp" | jq -r .artifactId)
curl -s -H "Authorization: Bearer $MAKESPDF_API_KEY" \
  "https://makespdf.com/api/v1/artifacts/$artifactId/pdf" -o enhanced.pdf
```

**Status response**

```json
{
  "jobId": "f8e1…",
  "status": "processing",
  "phase": "in-place",
  "progress": { "current": 17, "total": 50 },
  "mode": "in-place",
  "pageCount": 50,
  "inputFilename": "civic-cip.pdf",
  "artifactId": null,
  "downloadUrl": null,
  "creditsCharged": null,
  "errorMessage": null,
  "attemptCount": 1,
  "createdAt": "2026-05-06T10:00:00.000Z",
  "startedAt": "2026-05-06T10:00:01.500Z",
  "completedAt": null
}
```

Terminal states: `succeeded` (PDF ready, billed), `partial` (some pages failed,
no charge), `failed` (no charge), `cancelled`. On `succeeded`, `artifactId` and
`downloadUrl` are populated and a completion email is sent to your account
address.

**Related endpoints.** `GET /api/v1/enhance/jobs?status=…&limit=…&offset=…` lists
your jobs newest-first (owner-scoped, paginated; authed callers only).
`POST /api/v1/enhance/jobs/:id/cancel` flags a job for cancellation (best-effort
— pages already in flight finish).

**x402-paid wallet flow.** When you settle `POST /api/v1/enhance` with USDC via
x402 (`PAYMENT-SIGNATURE` header) instead of a Bearer key, the 202 envelope
additionally carries a `pollToken` — an opaque 32-byte bearer credential scoped
to that one job's lifetime. Re-present it as
`Authorization: Bearer <pollToken>` on the status, cancel, and artifact-download
calls. Token mismatch returns 404 (same shape as authed owner-mismatch).
Idempotent `PAYMENT-SIGNATURE` replays within 5 minutes return the cached
envelope verbatim, including the original pollToken. The list endpoint
`GET /api/v1/enhance/jobs` is not available to wallet callers — you know your
jobIds because the producer returned them.

## Data formatting

Dates in your data are automatically pre-formatted before rendering. Money values
are formatted by the template's `| currency` filter:

- **Dates:** `2025-03-15` becomes "15 March 2025". `2025-03` becomes "March
  2025".
- **Money:** `{{amount | currency}}` renders as `$1,234.50` by default (USD).
  Override per call with `{{amount | currency:AUD}}` → `A$1,234.50`, or
  `{{amount | currency:EUR:de-DE}}` for locale-specific formatting. Set a
  doc-wide default via `doc({ currency: "AUD" }, …)`. Accepts any ISO 4217 code
  (AUD, GBP, EUR, JPY, NZD, CAD, CHF, INR, …); unknown codes fall back to USD
  with a warning.

Send raw numeric values — the `| currency` filter handles symbols, thousands
separators, and decimal places.

## Supported document types

| Type | Description | Typical data |
| --- | --- | --- |
| `invoice` | Business invoices | Line items, totals, payment details, addresses |
| `receipt` | Transaction confirmations | Items, totals, payment method, store info |
| `quote` | Quotes and estimates | Itemised pricing, validity, terms |
| `cv` / `resume` | CVs and resumes | Experience, education, skills, contact info |
| `statement` | Account statements | Transactions, balances, date ranges |
| `certificate` | Certificates | Recipient, issuer, date, details |
| `letter` | Formal letters | Sender, recipient, subject, body paragraphs |

## Fillable forms

Templates can include real fillable AcroForm widgets that stay interactive in
Adobe Reader, Apple Preview, and any modern browser PDF viewer. Combined with
`tagged: true` on the document, the widgets land inside the structure tree and
become accessible to screen readers — the combination most form-capable PDF APIs
don't deliver.

Three DSL builders cover the common field types. `name` must be unique across the
document, and a `tooltip` is the field's accessible name (`/TU`) and required
for PDF/UA-1 conformance.

| Builder | PDF field | Required options |
| --- | --- | --- |
| `input(opts)` | `/Tx` text field | `name`, `width`, `height`. Optional: `value`, `tooltip`, `maxLength`, `multiline`. |
| `checkbox(opts)` | `/Btn` checkbox | `name`, `size`. Optional: `checked`, `tooltip`, `label` (renders box + text in a row). |
| `select(opts)` | `/Ch` combo dropdown | `name`, `width`, `height`, `options` (`[{ label, value }]`). Optional: `value`, `tooltip`. |

Minimal example — a name field, a single-select contact preference, and a consent
checkbox:

```js
const template = doc(
  { size: "A4", title: "Consent", tagged: true },
  page(
    s("h1", "Data processing consent"),
    s("label", "Full name"),
    input({ name: "fullName", width: 400, height: 18, tooltip: "Full legal name", maxLength: 120 }),
    gap(8),
    s("label", "Preferred contact"),
    select({
      name: "contactMethod", width: 200, height: 20,
      options: [
        { label: "Email",  value: "email" },
        { label: "Phone",  value: "phone" },
        { label: "Postal", value: "post"  },
      ],
      value: "email",
      tooltip: "How we should reach you",
    }),
    gap(8),
    checkbox({
      name: "consentProcessing", size: 12,
      tooltip: "Consent to data processing (required)",
      label: "I consent to the processing of my personal data.",
    }),
  ),
);
const sampleData = {};
```

A full government-style consent form, including the rendered PDF used as a
fixture in the per-release veraPDF gate, lives in the makesPDF repo at
`assets/samples/forms/`. Out of scope for v1: `/Sig` digital-signature fields,
radio-button groups (model with a `select` instead), and Acrobat-style
JavaScript field calculations.

## Errors

All errors return JSON with an `error` field:

```json
{
  "error": "Invalid request",
  "details": ["type: Required"]
}
```

| Status | Meaning |
| --- | --- |
| `400` | Invalid request body. Check the `details` array for field-level errors. |
| `404` | Template not found (wrong ID or not owned by your API key). |
| `429` | Rate limit exceeded. Check the `Retry-After` header for seconds until reset. |
| `500` | Internal error (AI failure, rendering error, etc.) |
| `503` | Service unavailable — no AI providers configured. |

The full error schema (`Error`) is in the
[OpenAPI spec](https://makespdf.com/openapi.json). Branch on the HTTP status first; when a
route sets a stable `code` or kebab-case `error` value, it is documented with
that endpoint.

## Rate limits

Every API response that counted against a limit carries the
[IETF RateLimit
headers](https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/),
one entry per limit the request counted against:

```http
RateLimit-Policy: "render";q=2000;w=3600
RateLimit: "render";r=1999;t=3600
```

`q` is the quota and `w` the window in seconds; `r` is how many requests remain
and `t` how many seconds until the oldest counted request leaves the sliding
window. A 429 also carries `Retry-After`, which takes precedence: wait that many
seconds before retrying.

## Versioning and deprecation

The API version is in the path: every endpoint lives under `/api/v1`. Within v1,
changes are additive only: new endpoints, new optional request fields, new
response fields. Ignore response fields you don’t recognise. Removing or renaming
a field, changing its type, or making an optional field required is a breaking
change and ships as a new version, never as an edit to v1.

If an endpoint is ever retired, it keeps working for at least 90 days after we
announce it. During that period its responses carry a `Deprecation` header (RFC
9745), a `Sunset` header with the retirement date (RFC 8594), and a `Link` to the
replacement. The announcement goes on the [updates feed](https://makespdf.com/updates). No
endpoint is deprecated today.
