Endpoint reference

POST /api/attach

Embed files in a PDF: an XML invoice, a spreadsheet, the source of a report. Each file gets a name, a MIME type, a description and a PDF/A-3 relationship. Returns the PDF as application/pdf.

A PDF can carry other files inside it. They are called attachments or embedded files. /api/attach adds them and sets the relationship value that e-invoice formats need. Listing and extracting attachments is not available in this API yet. Files you attached can be read with standard tools, for example qpdf --list-attachments file.pdf, qpdf --show-attachment=KEY file.pdf (KEY as printed by the list command), or pdfdetach -list file.pdf and pdfdetach -saveall file.pdf.

Request

Method: POST. URL: https://pdfops.dev/api/attach. Body: multipart/form-data.

FieldTypeRequiredDescription
pdfFile (PDF binary)YesExactly one PDF to add to, up to 4 MB and 2,000 pages.
fileFile, repeatedYes1 to 10 files to embed, one file field each, up to 3 MB combined. The PDF and the files together must stay under 4.5 MB, Vercel's platform request limit. A text value in a file field is refused. An empty file is allowed.
optionsString (JSON array)NoSettings per file. Entry i applies to file number i. See Options. Send the field once, as text.
passwordStringNoOpens a PDF that needs a user password. The output is not encrypted.

The optional X-API-Key header works as on /api/merge: no header is anonymous, 100 requests per IP per month; a valid key uses your tier's quota; an invalid or revoked key returns 401 invalid_api_key.

Options

Every key is optional. An unknown key is refused.

KeyTypeDefaultDescription
nameStringThe uploaded file name1 to 255 characters and at most 255 UTF-8 bytes (pdfdetach -saveall cannot write a longer file name). No / or \, no control characters, no unpaired surrogate. Must differ from every name already in the PDF and from the other files in the request.
mime_typeStringThe part's content typetype/subtype, for example text/xml. No parameters and no #. A content type on the part is used when it is valid and ignored when it is not.
descriptionStringNoneFree text stored with the file, at most 1,000 characters.
relationshipString"Unspecified"The PDF/A-3 AFRelationship: Alternative, Data, Source, Supplement or Unspecified.

Response

On success: 200 OK, Content-Type: application/pdf, body is the PDF with the files embedded. Page content, form fields and existing attachments are kept. Nothing is added unless every file is valid.

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

Limits

LimitValueWhen it is passed
PDF size, pages4 MB, 2,000 pagespdf_too_large, too_many_pages
Whole request4.5 MB413 request_too_large
Files per request10, 3 MB combinedtoo_many_files, files_too_large
Attachments in the PDF after the add200 distinct files with a file behind themtoo_many_attachments
Description1,000 charactersinvalid_description
Entries in the list of embedded files2,000 entries (with or without a file behind them) and 2 MB of keysname_tree_too_large
Nodes and slots visited in that list, however much is shared10,000name_tree_too_large
Reading the names already in the PDFA fixed budget that every distinct name or string read is charged against by its length: about half a second of work, thousands of 2,000-character namesattachments_too_complex

The add reads the existing names in the list of embedded files (each key and each entry's /UF and /F) to refuse a duplicate and to count what is there, so it has to read all of them, which is why these limits refuse instead of skipping. File-attachment annotations on pages and files that are only in the document's associated-files list are not read.

Error codes

Error codeStatusTrigger
invalid_multipart400Request body could not be parsed as multipart/form-data.
missing_pdf400The request does not have exactly one pdf file field.
pdf_too_large400The pdf file is over 4 MB.
invalid_pdf400The PDF could not be parsed (corrupt, or not a PDF), or its list of embedded files is malformed in a way an add cannot keep, such as two separate arrays that each end in a stray element.
encrypted_pdf400The PDF needs a password we were not given. Send it as the password form field.
decompressed_too_large400Object streams inside the PDF decompress to over 32 MB.
too_many_pages400The PDF has over 2,000 pages.
missing_files400No file field.
too_many_files400More than 10 file fields.
files_too_large400The file fields total more than 3 MB.
invalid_file400A file field holds a text value, not a file upload.
invalid_options400options is repeated, is a file, is not a JSON array, has more entries than files, or an entry has an unknown key or a value that is not a string.
invalid_name400A name is empty, over 255 characters or 255 UTF-8 bytes, has /, \, a control character or an unpaired surrogate.
invalid_mime_type400A mime_type is not type/subtype (no parameters, no #).
invalid_description400A description is over 1,000 characters or has an unpaired surrogate.
invalid_relationship400A relationship is not one of the five allowed values.
duplicate_name400A name is used twice in the request, or already exists in the PDF as an entry's key or as its /UF or /F name.
too_many_attachments400The PDF's attachments plus the new files would pass 200.
name_tree_too_large400The PDF's list of embedded files has over 2,000 entries, over 10,000 nodes and slots, or over 2 MB of keys. Attach rewrites that list and will not.
attachments_too_complex400Reading the names already in the PDF needs more than the work budget, or an existing name could not be read in full (its escapes outran the scan bound), so a duplicate cannot be ruled out.
save_failed500PDF serialization failed. Retryable.
internal_error500The output came out far larger than the input plus the files, and it was discarded.
request_too_large413The whole request body is over 4.5 MB (Vercel's platform request limit). Rejected before anything is parsed.
invalid_api_key401An X-API-Key header was sent but the key is unknown or revoked. Get a fresh key at /pricing.
rate_limited429The anonymous per-IP limit (100/month) or your key's monthly quota is used up. Retry-After gives seconds until next calendar month.

Example

Embed an XML file with the relationship Alternative:

curl -X POST https://pdfops.dev/api/attach \
  -F "pdf=@invoice.pdf" \
  -F "file=@invoice.xml;type=text/xml" \
  -F 'options=[{"name":"invoice.xml","description":"Invoice data","relationship":"Alternative"}]' \
  -o invoice-with-data.pdf

Embed two files. The first entry in options goes with the first file; the second file takes its name and type from the upload:

curl -X POST https://pdfops.dev/api/attach \
  -F "pdf=@report.pdf" \
  -F "file=@data.csv;type=text/csv" \
  -F "file=@notes.txt;type=text/plain" \
  -F 'options=[{"relationship":"Data"}]' \
  -o report-with-files.pdf

Check the result with a standard tool:

qpdf --list-attachments invoice-with-data.pdf
qpdf --show-attachment=invoice.xml invoice-with-data.pdf

Keyless calls work: 100 requests per IP per month with no key. With a key, add -H "X-API-Key: pdfops_live_..." to any request here; it raises your quota to your tier's.

Using this for real? A free API key raises the keyless 100 calls per IP to 250 requests a month, with no card.

Get a free API key

Code examples

Have an API key? Add an X-API-Key header to any request. It is optional, and it raises your quota from 100/IP/month to your tier's.

JavaScript (Node.js 22+), built-in fetch + FormData
import { readFile, writeFile } from 'node:fs/promises';

const fd = new FormData();
fd.append('pdf', new Blob([await readFile('invoice.pdf')], { type: 'application/pdf' }), 'invoice.pdf');
fd.append('file', new Blob([await readFile('invoice.xml')], { type: 'text/xml' }), 'invoice.xml');
fd.append('options', JSON.stringify([{ name: 'invoice.xml', relationship: 'Alternative' }]));

// The key is optional: send the header only when you have one.
const headers = process.env.PDFOPS_API_KEY ? { 'X-API-Key': process.env.PDFOPS_API_KEY } : {};
const res = await fetch('https://pdfops.dev/api/attach', { method: 'POST', headers, body: fd });
if (!res.ok) {
  const err = await res.json();
  throw new Error(`PDFops attach failed: ${err.error}: ${err.details}`);
}
await writeFile('invoice-with-data.pdf', Buffer.from(await res.arrayBuffer()));
Python, requests
import json, os, requests

options = [{"name": "invoice.xml", "relationship": "Alternative"}]
# The key is optional: send the header only when you have one.
headers = {"X-API-Key": os.environ["PDFOPS_API_KEY"]} if os.environ.get("PDFOPS_API_KEY") else {}
with open("invoice.pdf", "rb") as pdf, open("invoice.xml", "rb") as xml:
    res = requests.post(
        "https://pdfops.dev/api/attach",
        headers=headers,
        files=[
            ("pdf", ("invoice.pdf", pdf, "application/pdf")),
            ("file", ("invoice.xml", xml, "text/xml")),
        ],
        data={"options": json.dumps(options)},
    )
res.raise_for_status()
open("invoice-with-data.pdf", "wb").write(res.content)

From an AI agent (MCP)

The hosted MCP server at https://pdfops.dev/api/mcp exposes this as the pdf_add_attachment tool. It takes pdf_path and files, a list of { source, name, mime_type, description, relationship } where source is an https:// URL or a data: URI, and an optional password. The name defaults to the last part of an https:// URL path. The tool returns the PDF inline. Calls count like REST calls. See Remote (hosted) MCP.

Behavioral notes

FAQ

How do I attach a file to a PDF with an API?

Send the PDF in a pdf field and the file in a file field to /api/attach. Optional settings (name, mime_type, description, relationship) go in an options field as a JSON array, one object per file. The response is the PDF with the file embedded. Page content, form fields and existing attachments are kept. The whole file is saved again, so a digital signature the PDF already had will no longer validate.

What does the relationship value mean?

It is the PDF/A-3 AFRelationship name that says how the file relates to the document: Alternative, Data, Source, Supplement or Unspecified. E-invoice formats such as Factur-X use Alternative for the XML invoice. The default is Unspecified.

How do I read the files I attached?

This API does not list or extract attachments yet. Standard tools do: qpdf --list-attachments and qpdf --show-attachment=KEY file.pdf (KEY as printed by the list command), or pdfdetach -list and pdfdetach -saveall file.pdf.

Why was a name refused when I added a file?

A name must be 1 to 255 characters (and at most 255 UTF-8 bytes) with no slash, backslash or control characters, and it cannot match a name already in the PDF or another file in the same request. The error is invalid_name or duplicate_name, and details names the file.

Related: Read metadata · Merge PDFs · Encrypt a PDF.

Get a free API key. Keyless calls get 100 requests per IP per month; a free key raises that to 250, with no card. Enter your email and the key arrives in your inbox.

Get a free API key