Endpoint reference

POST /api/invoice

Generate a complete, professionally laid-out US-Letter invoice PDF from a JSON body — header, FROM/BILL TO blocks, items table, totals, notes. No template upload. Deterministic: the same JSON returns a byte-identical PDF. A worked request with its real response is at JSON to invoice PDF. Prefer a form? The free generator at /tools/invoice calls this endpoint.

This is the first PDFops endpoint that ships its own template: /api/fill-form fills an AcroForm PDF you bring; /api/invoice draws the whole document from data. That makes it a natural fit for a Stripe webhook that turns a payment into an invoice PDF, a monthly billing cron, or freelancer tooling — see the Stripe walkthrough and the invoices use case.

Request

Method: POST. URL: https://pdfops.dev/api/invoice. Body: application/json.

FieldTypeRequiredDescription
fromstring or objectYesSeller, rendered in the FROM block. A plain string ("Acme Studio LLC"), or { name, lines } where lines is up to 6 address lines rendered under the name.
tostring or objectYesBuyer, rendered in the BILL TO block. Same shape as from. If the name is empty, blank or missing and one to.lines entry is an email address, the first such entry is printed as the recipient and the response carries an X-Pdfops-Warning note. An address line or tax id is never promoted to a name. With neither a name nor an email line the call is a 400 invalid_to; no placeholder name is invented. from always needs a name. Not available with e_invoice. See Sparse and loosely formatted input.
itemsarrayYes1 to 100 line items — schema below.
invoice_numberstringNoPrinted in the invoice header.
datestring or integerNoInvoice date, always printed in the header as YYYY-MM-DD. Accepts YYYY-MM-DD, an ISO 8601 datetime, a Unix timestamp and unambiguous slash or dot dates (formats below); anything else is a 400 invalid_date that names the accepted formats. Omit it and no date line is printed. Also pins the PDF's metadata dates — pass it explicitly for byte-identical re-renders (see Deterministic output).
duestring or numberNoDue date, printed in the header as given (trimmed), so free text such as Net 30 works, and so does a date written with slashes or dots: it is never rewritten, so one caller's invoices do not mix formats. Only a Unix timestamp (a number or a string of digits, same ranges as date) or a full ISO 8601 datetime is converted to YYYY-MM-DD; a timestamp adds an X-Pdfops-Warning note. A number that is not a valid timestamp (0, -5, 1.5) is left off the invoice, with a note naming it.
currencystringNoISO 4217 code, default USD. Formatting only, e.g. USD 1,200.00 — no conversion.
tax_ratenumberNoPercent, 0 to 100, as a JSON number or a plain numeric string such as "8.5". Adds a tax line between subtotal and total.
notesstringNoFree-text block rendered under the totals.
e_invoicestringNo"factur-x" returns a Factur-X (ZUGFeRD) e-invoice, which makes more fields required and adds tax_category, tax_exemption_reason, payment_terms, iban, unit and party fields. See below.

Each entry in items:

FieldTypeRequiredDescription
descriptionstringYesWhat the line is for.
quantitynumberNoA JSON number or a plain numeric string such as "3", > 0. Defaults to 1.
unit_pricenumberYesPrice per unit as a JSON number or a plain numeric string such as "10.99", ≥ 0, in the invoice currency. Currency symbols ($10.99), thousands separators (1,000) and exponents are refused, because they can mean more than one amount. The line amount is quantity × unit_price.
HeaderRequiredDescription
X-API-KeyNoOptional. Same auth semantics as /api/fill-form and /api/merge: no header → anonymous, 100 requests/IP/month; valid key → your tier's quota; invalid or revoked key → 401 invalid_api_key.

Successful (2xx) calls count 1 request against your quota — the same meter as the other PDF endpoints. Check consumption with GET /api/usage.

Full request example

{
  "from": { "name": "Acme Studio LLC", "lines": ["100 Main St", "Portland, OR 97201"] },
  "to": "Globex Corporation",
  "invoice_number": "INV-0042",
  "date": "2026-07-21",
  "due": "2026-08-20",
  "currency": "USD",
  "tax_rate": 8.5,
  "items": [
    { "description": "Design retainer — July", "quantity": 1, "unit_price": 2400 },
    { "description": "Landing page build", "quantity": 3, "unit_price": 650 }
  ],
  "notes": "Payment by bank transfer within 30 days."
}

Response

On success: 200 OK, Content-Type: application/pdf — a complete US-Letter invoice:

When the call read something in a way you might not expect (a timestamp read as a UTC date, a slash date converted to YYYY-MM-DD, an email used as the recipient, a numeric due left off), the response carries an X-Pdfops-Warning header (several notes are separated by ; ), for example date: 1764201600 read as 2025-11-27 (Unix seconds, UTC). The header is absent when nothing was changed, and the body is always the PDF. The hosted MCP tool returns the same text as a warning field. Whether a client library or integration (Zapier, Make, n8n, the npm MCP server, the TypeScript SDK) passes it on depends on its version; if yours does not, read the response header.

On any failure: 4xx, Content-Type: application/json, body is { "error": "<code>", "details": "<explanation>" }.

Keep the complete work description on the invoice

Put the agreed work in each line item and the remittance instructions in notes. Long descriptions wrap below the first line, beside the same quantity and amount. A field that exceeds its printable limit returns HTTP 400 with the field name. Edit the source and retry. Download the example request to reproduce the walkthrough.

See a complete work order, the over-limit response and a successful retry. Download the video.

Sparse and loosely formatted input

Automation platforms send what their source has: a Stripe payment may have no customer name and a Unix-timestamp date, a spreadsheet may hold 11/27/2026. The endpoint reads the shapes that mean one thing and refuses the rest. It never guesses a locale.

Input for dateResult
2026-11-27Used as is.
2026-11-27T23:30:00-05:00, 2026-11-27T10:00:00Z, 2026-11-27T10:00The date as written is used (2026-11-27), with no warning; with no offset, UTC is assumed. A space instead of T is refused.
1764201600 (seconds), 1764201600000 (milliseconds)A whole number, as a JSON number or a string of digits (no sign, leading zeros or decimals), read as UTC (2025-11-27). Decided by value: seconds from 946684800 to 4102444800, milliseconds from 946684800000 to 4102444800000 (2000-01-01 to 2100-01-01). Any other number is a 400, including 20261127, which is not read as YYYYMMDD.
11/27/2026, 27/11/2026, 27.11.2026Read when one of the first two parts is above 12 (it must be the day), or when both are equal (03/03/2026). Four-digit year required (13/1/26 is a 400). A zero or out-of-range part (0/5/2026, 13/13/2026) is an invalid date, not an ambiguous one.
2026/11/27, 2026.11.27Year, month, day.
03/04/2026400 invalid_date: it is 3 April or 4 March depending on locale. Send YYYY-MM-DD.

Whatever the form, the year must be between 1900 and 2100 (so 0100-01-01 and 9999-12-31 are a 400), and surrounding whitespace is ignored. A timestamp or slash date is reported in X-Pdfops-Warning (an ISO datetime is not: it is the date it states), and the PDF prints and pins the resulting YYYY-MM-DD.

None of this applies with e_invoice. A Factur-X request keeps strict input: date and due must be exactly YYYY-MM-DD calendar dates, quantity, unit_price and tax_rate must be JSON numbers, and to needs its name. A loose value is a 400 that says e-invoices require strict input, and no X-Pdfops-Warning header is sent.

Ordinary invoices print up to 200 characters per party name, address line or item description, six address lines per party, and 1,000 characters of notes. Long descriptions and notes wrap across lines and continue onto another page when needed. If a field exceeds its limit or a header cannot fit, the API returns HTTP 400 with the field name. Check the returned error before retrying.

Recipient: when to.name is empty or missing and a to.lines entry has the shape of an email address, the first such entry becomes the recipient line (the other lines stay under it, in order) and the response notes it. An email counts only if it is a plain address: one @, a local part without edge or doubled dots, a domain of letters, digits and hyphens ending in two or more letters, at most 254 characters. One longer than 200 characters is refused (400 invalid_to) rather than cut. to.lines is validated first, so a malformed array is a 400 either way. When there is no name and no email line (only a street, a tax id or a country code, say), the call is a 400 invalid_to asking for a name or the customer's email as one of the lines.

Numbers: quantity, unit_price and tax_rate accept JSON numbers or plain numeric strings of at most 40 characters ("10.99", " 3 ", "+5"). An empty string, a currency symbol, a thousands separator or an exponent is a 400 whose message names the field and the value received.

Factur-X / ZUGFeRD e-invoice output

Add "e_invoice": "factur-x" to the request and the response is a PDF/A-3 file that carries the invoice data as an embedded factur-x.xml (UN/CEFACT Cross Industry Invoice, profile EN 16931, also called COMFORT). The XMP metadata declares PDF/A-3B and the Factur-X extension schema (document type INVOICE, file name, version 1.0, conformance level EN 16931), the font is embedded and the file has an sRGB output intent and a document ID. Without e_invoice (absent, null, false or an empty string) nothing changes: the request, the validation and the output bytes are exactly the plain invoice, and the extra fields below are ignored. Any other value that is not "factur-x" is a 400 invalid_einvoice_field. With e_invoice set, a field this mode does not honour is refused rather than ignored: per-item tax fields (the rate and category apply to the whole invoice) and unknown fields.

What was checked. The output of every variant in the test suite (standard, zero-rated, exempt, reverse charge, not subject to VAT, payment terms only, rounding edge cases, 100 items over several pages, markup characters in text fields) is validated with the Mustang validator 2.26.0 (PDF/A-3 through veraPDF, the Factur-X XSD for EN 16931 and the EN 16931 schematron), and a file counts only when both the PDF/A half and the XML half pass. The same validator rejects deliberately broken files, on the half each one breaks. That is a statement about the tests we ran. It is not a certification, and it is not advice on what a tax authority or a buyer's system will accept in a given country.

What is not produced. Only the EN 16931 profile of Factur-X (ZUGFeRD). No XRechnung, Peppol or UBL output, no MINIMUM, BASIC WL, BASIC or EXTENDED profile, no credit notes, discounts or charges, no prepaid amounts, no delivery data, and one VAT category and rate per invoice.

With e_invoice set these fields become required. A request that misses any of them is a 400 einvoice_fields_required whose body lists every missing field in a missing array.

FieldRule
invoice_number, dateRequired. date is a YYYY-MM-DD calendar date.
currencyRequired, no default. An ISO 4217 code accepted by EN 16931. Amounts always have 2 decimals, whatever the currency.
due or payment_termsOne of them is required. due must be a YYYY-MM-DD calendar date in this mode. Optional iban (checksum verified) adds a payment means: SEPA credit transfer (code 58) when the invoice is in EUR and the IBAN is in the SEPA area, otherwise credit transfer (code 30).
from, toObjects, not strings: name and country (ISO 3166-1 alpha-2, capitals; 1A for Kosovo) are required. Optional: street, postcode, city, vat_id, tax_id, registration_id. The existing lines stay as extra lines on the page only; they are not in the XML.
Seller identificationfrom.vat_id, or from.tax_id together with from.registration_id. For tax_category O, from.registration_id and no VAT ids on either party. A vat_id must start with a two-letter country prefix in capitals (DE123456789, EL for Greece). The buyer has no tax number in EN 16931: to.tax_id is refused, use to.vat_id.
items[].unitRequired on every item: a UN/ECE Recommendation 20 unit code such as C62 (one), HUR (hour) or KGM (kilogram), from the EN 16931 code list.
tax_categoryS standard rate (the default when tax_rate is above 0), Z zero rate, E exempt, AE reverse charge, O not subject to VAT. Required when tax_rate is 0 or omitted. tax_rate must be 0 for every category except S.
tax_exemption_reasonRequired for E, AE and O, refused for S and Z. For AE the buyer also needs vat_id or registration_id.

The other EN 16931 categories (G, K, L, M) are refused with invalid_einvoice_field: they carry delivery rules this endpoint does not collect.

Totals: one calculation for the page and the XML

The amounts in the XML and the amounts on the page come from the same code, so they cannot disagree. All arithmetic is exact decimal arithmetic on integers, never floating point. quantity and unit_price take at most 4 decimals and tax_rate at most 2 (more is a 400, never a silent rounding). Each line amount is quantity × unit_price rounded half up to 2 decimals. The document line total is the sum of those rounded line amounts. VAT is computed once on that sum (basis × rate / 100, rounded half up to 2 decimals), not per line. The grand total is basis plus VAT and equals the amount due. Amounts above 9999999999999.99 are refused.

Text

XML cannot carry control characters or lone surrogates, and the embedded font covers Basic Latin, Latin-1, Latin Extended-A, the euro sign and common punctuation. In this mode leading and trailing whitespace is trimmed and nothing else is changed. Text that is longer than its limit (200 characters; 1,000 for notes), contains characters XML 1.0 cannot carry, or contains characters the font cannot draw is refused with a 400 naming the field: invalid_einvoice_field for the first two, unrenderable_text for the last. Text that is accepted is never cut: long descriptions, names, payment terms and notes wrap onto further lines (and pages) on the page and are carried in full in the XML. Amounts are laid out from their measured width, so they do not overprint; at the largest accepted values the numeric columns shrink to as small as 7 points. Right-to-left scripts, Cyrillic, Greek, CJK and emoji are therefore refused. notes may contain line breaks and tabs. Markup characters such as &, < and ]]> are escaped and come back unchanged.

Example

curl -X POST https://pdfops.dev/api/invoice \
  -H "Content-Type: application/json" \
  -H "X-API-Key: pdfops_live_..." \
  -d '{
    "e_invoice": "factur-x",
    "from": { "name": "Lieferant GmbH", "street": "Lieferantenstrasse 20", "postcode": "80333",
              "city": "München", "country": "DE", "vat_id": "DE123456789" },
    "to": { "name": "Kunden AG", "city": "Paris", "country": "FR" },
    "invoice_number": "RE-2026-0042",
    "date": "2026-11-21",
    "due": "2026-12-21",
    "currency": "EUR",
    "tax_rate": 19,
    "iban": "DE02 1203 0000 0000 2020 51",
    "items": [
      { "description": "Beratung", "quantity": 10.5, "unit": "HUR", "unit_price": 120 },
      { "description": "Trennblätter A4", "quantity": 20, "unit": "C62", "unit_price": 9.9 }
    ]
  }' \
  -o RE-2026-0042.pdf

# read the embedded XML back (poppler-utils)
pdfdetach -save 1 -o factur-x.xml RE-2026-0042.pdf

The X-API-Key header is optional, and a free key comes from pdfops.dev/pricing.

Here the lines are 1,260.00 and 198.00, VAT at 19% on 1,458.00 is 277.02 and the total is 1,735.02, in the XML and on the page. A request that omits unit and from.country returns:

{ "error": "einvoice_fields_required",
  "details": "e_invoice \"factur-x\" also requires: from.country, items[0].unit",
  "missing": ["from.country", "items[0].unit"] }

The call counts as 1 request, like a plain invoice. The output is deterministic in this mode too: the same JSON returns the same bytes.

Deterministic output

The same JSON body returns a byte-identical PDF — every time. The PDF's internal metadata dates are pinned to the invoice date rather than the render time, so nothing in the file varies between runs. Hash the output today, render the same JSON tomorrow, get the same hash.

Practically, that means re-rendering is idempotent and safe: a Stripe webhook that retries, a monthly cron that re-runs, or a "regenerate" button that fires twice all produce the same file — dedup, caching, content-addressed storage, and audit diffs just work. There is no wall-clock input at all: the PDF's metadata dates are pinned to your date when given, and to a fixed epoch otherwise — never to render time — so a body that omits date is still byte-stable across days (it just has no date line on the document).

Branding

Anonymous calls and Free-tier keys produce PDFs with a small "Generated with pdfops.dev" footer line. Indie and Pro keys produce clean output with no branding — see /pricing.

Error codes

Error codeStatusTrigger
invalid_json400Request body isn't parseable JSON.
invalid_body400Body parsed but isn't a JSON object with the required fields.
invalid_from400from missing or the wrong shape — must be a non-empty string or { name, lines } with at most 6 lines. A name and lines that wrap to more than about 30 lines in the 240 pt column are refused rather than cut off (the same applies to to, as invalid_to).
invalid_to400to missing, the wrong shape, or with nothing that identifies the recipient: send a non-empty to string or to.name, or include the customer's email as one of the to.lines entries.
invalid_items400items missing, empty, longer than 100, or an item fails validation (missing description, quantity ≤ 0, unit_price < 0, or either one neither a number nor a plain numeric string). The message names the field and the value received.
invalid_currency400currency isn't an ISO 4217 code.
invalid_tax_rate400tax_rate isn't a number between 0 and 100.
invalid_date400date isn't a real calendar date in one of the accepted formats, or is an ambiguous slash date such as 03/04/2026. The message names the value received and the accepted formats.
unrenderable_text400A text field contains characters the font can't draw (the built-in font covers Latin-1 / WinAnsi; with e_invoice the embedded font covers Latin, Latin Extended-A, the euro sign and common punctuation; no emoji or CJK in either). details names the field.
einvoice_fields_required400e_invoice is set and required fields are missing. missing lists every one. See Factur-X output.
invalid_einvoice_field400e_invoice is set and a field has a bad value: unknown country, currency, unit or category, a date that is not YYYY-MM-DD, more decimals than allowed, text that is too long or cannot be written in XML, a rule broken between fields. details names the field.
request_too_large413The whole request body is over 1 MB. Rejected before anything is parsed.
invalid_api_key401An X-API-Key header was sent but the key is unknown or revoked. No fallback to the anonymous IP cap — get a fresh key at /pricing.
rate_limited (anonymous)429No X-API-Key header and the per-IP limit (100/month) is exhausted. Retry-After header gives seconds until next calendar month.
rate_limited (keyed)429Your key's tier quota (Free 250 / Indie 4,000 / Pro 25,000 per month) is exhausted. Retry-After header gives seconds until next calendar month.

Example — curl

curl -X POST https://pdfops.dev/api/invoice \
  -H "Content-Type: application/json" \
  -H "X-API-Key: pdfops_live_..." \
  -d '{
    "from": "Acme Studio LLC",
    "to": "Globex Corporation",
    "invoice_number": "INV-0042",
    "date": "2026-07-21",
    "items": [
      { "description": "Design retainer — July", "unit_price": 2400 }
    ]
  }' \
  -o invoice-INV-0042.pdf

The X-API-Key header is optional — drop it to use the anonymous quota (the PDF then carries the footer line). A free key comes from pdfops.dev/pricing.

Example — JavaScript: Stripe webhook → invoice PDF

The marquee pattern from the Stripe walkthrough: a Worker receives an invoice.paid event and renders the PDF. Because output is deterministic, Stripe's webhook retries re-produce the identical file — store it keyed by hash or invoice number and duplicates collapse for free.

export default {
  async fetch(req, env) {
    const event = await req.json(); // Stripe webhook — verify the signature first
    const inv = event.data.object;  // an invoice.paid Invoice object

    const res = await fetch('https://pdfops.dev/api/invoice', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-API-Key': env.PDFOPS_KEY,
      },
      body: JSON.stringify({
        from: { name: 'Acme Studio LLC', lines: ['100 Main St', 'Portland, OR 97201'] },
        to: inv.customer_name,
        invoice_number: inv.number,
        date: new Date(inv.created * 1000).toISOString().slice(0, 10),
        currency: inv.currency.toUpperCase(),
        items: inv.lines.data.map((line) => ({
          description: line.description,
          quantity: line.quantity,
          unit_price: line.amount / 100 / line.quantity,
        })),
      }),
    });

    const pdf = await res.arrayBuffer();
    await env.BUCKET.put(`invoices/${inv.number}.pdf`, pdf); // R2, email it, etc.
    return new Response('ok');
  },
};

FAQ

Why does deterministic output matter?

Because re-renders become free and safe. The same JSON returns a byte-identical PDF — hash the output today, render the same JSON tomorrow, get the same hash. Webhook retries and cron re-runs produce the same file instead of near-duplicates, so dedup, caching, diffing, and audit trails all work. There is no wall-clock input at all: metadata dates are pinned to the invoice date when you pass one, and to a fixed epoch otherwise — never to render time. Omitting date simply leaves the date line off the document; the output stays byte-stable either way.

How do I remove the "Generated with pdfops.dev" footer line?

Use a paid key. Anonymous calls and Free-tier keys produce PDFs with a small "Generated with pdfops.dev" footer line; Indie and Pro keys produce clean output with no branding. Plans are at /pricing.

Can I customize the invoice layout?

Not yet — there's one clean US-Letter template, and every knob the endpoint exposes (parties, dates, currency, tax, notes) feeds it. If you need a specific layout, logo, or paper size, tell us via the feedback form at POST /api/waitlist — layout requests directly shape what we build next.

How are currencies handled?

currency takes any ISO 4217 code (default USD) and controls formatting only: amounts render as the code plus a grouped two-decimal number, e.g. USD 1,200.00 or EUR 850.00. There's no exchange-rate conversion — the numbers you send are the numbers printed.

Does /api/invoice consume my quota?

Yes — a successful (2xx) call counts as 1 request against the same monthly quota as the other PDF endpoints (anonymous 100/IP/month, or your key's tier). Failed requests (4xx/5xx) don't consume budget.

Does it produce XRechnung, Peppol or UBL?

No. The only e-invoice output is Factur-X (ZUGFeRD), profile EN 16931, as a PDF/A-3 file with the XML embedded. It was checked with the Mustang validator 2.26.0; other formats and profiles are not built, and nothing here is a statement of legal compliance in any country.

How do I get the XML out of the e-invoice PDF?

It is an embedded file named factur-x.xml. With poppler-utils, pdfdetach -save 1 -o factur-x.xml invoice.pdf; with qpdf, qpdf --show-attachment=factur-x.xml invoice.pdf > factur-x.xml.