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.
| Field | Type | Required | Description |
|---|---|---|---|
pdf | File (PDF binary) | Yes | Exactly one PDF to add to, up to 4 MB and 2,000 pages. |
file | File, repeated | Yes | 1 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. |
options | String (JSON array) | No | Settings per file. Entry i applies to file number i. See Options. Send the field once, as text. |
password | String | No | Opens 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.
| Key | Type | Default | Description |
|---|---|---|---|
name | String | The uploaded file name | 1 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_type | String | The part's content type | type/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. |
description | String | None | Free text stored with the file, at most 1,000 characters. |
relationship | String | "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
| Limit | Value | When it is passed |
|---|---|---|
| PDF size, pages | 4 MB, 2,000 pages | pdf_too_large, too_many_pages |
| Whole request | 4.5 MB | 413 request_too_large |
| Files per request | 10, 3 MB combined | too_many_files, files_too_large |
| Attachments in the PDF after the add | 200 distinct files with a file behind them | too_many_attachments |
| Description | 1,000 characters | invalid_description |
| Entries in the list of embedded files | 2,000 entries (with or without a file behind them) and 2 MB of keys | name_tree_too_large |
| Nodes and slots visited in that list, however much is shared | 10,000 | name_tree_too_large |
| Reading the names already in the PDF | A 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 names | attachments_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 code | Status | Trigger |
|---|---|---|
invalid_multipart | 400 | Request body could not be parsed as multipart/form-data. |
missing_pdf | 400 | The request does not have exactly one pdf file field. |
pdf_too_large | 400 | The pdf file is over 4 MB. |
invalid_pdf | 400 | The 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_pdf | 400 | The PDF needs a password we were not given. Send it as the password form field. |
decompressed_too_large | 400 | Object streams inside the PDF decompress to over 32 MB. |
too_many_pages | 400 | The PDF has over 2,000 pages. |
missing_files | 400 | No file field. |
too_many_files | 400 | More than 10 file fields. |
files_too_large | 400 | The file fields total more than 3 MB. |
invalid_file | 400 | A file field holds a text value, not a file upload. |
invalid_options | 400 | options 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_name | 400 | A name is empty, over 255 characters or 255 UTF-8 bytes, has /, \, a control character or an unpaired surrogate. |
invalid_mime_type | 400 | A mime_type is not type/subtype (no parameters, no #). |
invalid_description | 400 | A description is over 1,000 characters or has an unpaired surrogate. |
invalid_relationship | 400 | A relationship is not one of the five allowed values. |
duplicate_name | 400 | A 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_attachments | 400 | The PDF's attachments plus the new files would pass 200. |
name_tree_too_large | 400 | The 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_complex | 400 | Reading 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_failed | 500 | PDF serialization failed. Retryable. |
internal_error | 500 | The output came out far larger than the input plus the files, and it was discarded. |
request_too_large | 413 | The whole request body is over 4.5 MB (Vercel's platform request limit). Rejected before anything is parsed. |
invalid_api_key | 401 | An X-API-Key header was sent but the key is unknown or revoked. Get a fresh key at /pricing. |
rate_limited | 429 | The 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.
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
- A signed PDF stops validating after an add. The whole file is saved again, which invalidates an existing digital signature.
/api/inspectlists a signature field but does not say whether it is signed, so check in a PDF viewer before adding to a signed document. - The list of embedded files is rewritten, and no existing key is touched. The file is written as a standard embedded file with a file specification and added to the document's associated-files list so the relationship is visible to PDF/A-3 tools. A list that was split into several nodes becomes one flat list and a stored
/Limitsis dropped. Existing keys keep their bytes and order; each new key goes in before the first existing key that sorts after it, and the old list nodes that nothing else uses are removed, so many small adds do not grow the file. Entries that are not a (string key, value) pair, and one stray last element, are kept but moved to the end of the list. A name tree node or/EmbeddedFilesentry that is really a page tree, a page or the catalog is refused withinvalid_pdf. - Names and keys. Each file keeps its full name in the file specification, so viewers show it as written. The key the list files it under is plain ASCII: the name itself when that is printable ASCII, otherwise the name with every other character replaced by
_and a hash of the full name before the extension. The keys come back in thex-pdfops-attachment-keysresponse header, a JSON array of{name, key}(the name cut to 40 characters). To extract with qpdf, use the key thatqpdf --list-attachments file.pdfprints:qpdf --list-attachments file.pdf qpdf --show-attachment=KEY file.pdf > out.binpdfdetach -list file.pdfshows the real names. One limit to know about:qpdf --show-attachmentfinds a key by binary search on decoded text. In a PDF whose existing keys are not in that order (keys with PDFDocEncoding characters such as an en dash, a bullet or accented capitals like Ž, or UTF-16 keys that mix emoji with private-use or fullwidth characters), adding a file can make qpdf miss keys it found before, and miss the new one.qpdf --add-attachmenthas the same effect on such files. Every file is still in the PDF:qpdf --list-attachmentsandpdfdetachshow and save all of them. With plain ASCII, Latin-1 or ordinary UTF-16 keys this does not happen. Some libraries (pdf-lib, PyMuPDF) show the key in place of the name; for a non-ASCII name that is the ASCII form above. - No attachment dates are written. The modification date and producer are pinned and an existing creation date is kept. Each attached file comes back byte for byte when extracted; the bytes of the PDF around it can differ between runtime versions, so do not hash the output.
- What
/api/attachdoes not do. It does not create page-level attachment annotations, does not convert a file, and does not make a PDF/A-3 document by itself: it embeds the file and sets the relationship. Whether the whole document conforms is up to its other contents. - Limits: 4 MB per PDF, 2,000 pages, 10 files and 3 MB of files per add, 200 attachments in the finished PDF, 4.5 MB per request (Vercel's platform limit).
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.