← Back to blog

Fill PDF Forms from JSON: AcroForm Fields and Flattening

October 30, 2026 · Eric · 7 min read

Filling a PDF form is one of those tasks that looks trivial until you try to automate it. The document on screen has a box labelled “Vendor name”; the PDF has a field called VND_NM_1. Coordinates drift between revisions, text doesn't fit, and the checkbox refuses to tick. If an agent is supposed to fill a W-9, an intake form, or a lease addendum, guessing coordinates is the wrong layer to work at.

AcroForm PDFs give you a better handle: named fields, typed values, and a form dictionary the file ships with. Two endpoints cover it — one to read the field list, one to write values into it. Here is the two-step loop, the value conventions that trip people up, and the delivery step (flatten, stamp, page numbers) that turns a filled form into something you can hand to a counterparty.

What "filling" actually means

A fillable PDF contains an AcroForm dictionary listing every field with a name, a type, and optional flags. Tools like pdf-lib read that dictionary, set values on the field objects, and save a new file. The visual layout is untouched — only the field values change.

That definition sets the boundary honestly:

Step 1: list the fields before you fill anything

Field names are the whole contract, and you cannot trust the label printed on the page to match them. Start by asking the document what it contains. Send the PDF as multipart form data:

curl -s -F "pdf=@vendor-intake.pdf" \
  https://agentmediatools.com/api/pdf-list-fields

Real response from a small intake form I generated for this test:

{
  "success": true,
  "fields": [
    { "name": "vendor_name", "type": "TextField" },
    { "name": "contact_email", "type": "TextField" },
    { "name": "account_number", "type": "TextField" },
    { "name": "accept_terms", "type": "CheckBox" },
    { "name": "country", "type": "Dropdown" }
  ],
  "count": 5
}

Types come back in the vocabulary of the underlying library: TextField, CheckBox, Dropdown, RadioGroup, OptionList, Signature. The type matters because each one expects a different value shape in the next step.

Instead of a local file you can pass a public URL with -F "url=https://...". Field discovery is also the cheapest possible sanity check on a new template: cache the field list once per document revision and you never have to guess again.

Step 2: fill the fields from a JSON map

Send the same PDF with a fields parameter containing a JSON object of field name to value:

curl -s -F "pdf=@vendor-intake.pdf" \
  -F 'fields={"vendor_name":"Ada Lovelace","contact_email":"ada@example.com","accept_terms":true,"country":"CA"}' \
  https://agentmediatools.com/api/pdf-form-fill

Response:

{
  "success": true,
  "filename": "3aeee3d1-b158-4c58-8af3-d3de6614b9b1.pdf",
  "downloadUrl": "/downloads/3aeee3d1-b158-4c58-8af3-d3de6614b9b1.pdf",
  "size": 4969,
  "filled_fields": ["vendor_name", "contact_email", "accept_terms", "country"],
  "missing_fields": [],
  "available_fields": ["vendor_name", "contact_email", "account_number", "accept_terms", "country"],
  "flattened": false
}

Three details in that payload are worth designing around:

Value conventions per field type

This is where most integrations fail quietly. The endpoint inspects each field's type and coerces the value:

Field typeWhat to sendBehavior
TextFieldstring or numberConverted to a string and set as the field value
CheckBoxtrue, "true", "1", "Yes", "yes"Checks the box; any other value unchecks it
Dropdownthe exact option stringMust match an option already in the list, or the field lands in missing_fields
RadioGroupthe exact option stringSame rule as dropdowns — no option, no fill

Two consequences follow. First, "accept_terms": "no" doesn't leave the box alone — it actively unchecks it, which is what you want for a deterministic pipeline but surprising if you were passing a value through. Second, dropdowns and radios need the option value, not the label: if the choice list is ["US","CA","MX"], send CA — not Canada. When you don't know the option strings, a failed fill with missing_fields: ["country"] is your signal to inspect the template, not to retry harder.

Text fields stringify both strings and numbers, so amounts and IDs are safe as either. They are never reformatted, though: send the exact printed string you want for dates, phone numbers, and currency, or the page will show whatever you sent.

Step 3: flatten, stamp, and number pages for delivery

An unflattened output is still a form — fields remain editable. For anything you send to a client, a landlord, or a filing portal, flatten it so values become part of the page content:

curl -s -F "pdf=@vendor-intake.pdf" \
  -F 'fields={"vendor_name":"Ada Lovelace","accept_terms":true,"country":"CA"}' \
  -F "flatten=true" \
  -F "stamp_text=Received 2026-10-30" \
  -F "page_numbers=true" \
  https://agentmediatools.com/api/pdf-form-fill

What each option does, exactly:

Ordering inside the request is fixed: values are set first, then the form is flattened, then the stamp and page numbers are drawn. That's why a stamp survives flattening and why values never appear as editable text under it.

The same flow in Python

A complete, copy-pasteable script: discover fields, fill, download, and print anything that didn't take.

import json

import requests

BASE = "https://agentmediatools.com"
pdf_path = "vendor-intake.pdf"

# 1. Discover field names and types
with open(pdf_path, "rb") as fh:
    listing = requests.post(
        f"{BASE}/api/pdf-list-fields",
        files={"pdf": fh},
        timeout=60,
    ).json()

print("fields:", [(f["name"], f["type"]) for f in listing["fields"]])

# 2. Build the value map from your own data
values = {
    "vendor_name": "Ada Lovelace",
    "contact_email": "ada@example.com",
    "accept_terms": True,
    "country": "CA",
}

# 3. Fill, flatten, and stamp
with open(pdf_path, "rb") as fh:
    result = requests.post(
        f"{BASE}/api/pdf-form-fill",
        files={"pdf": fh},
        data={
            "fields": json.dumps(values),
            "flatten": "true",
            "stamp_text": "Received 2026-10-30",
            "page_numbers": "true",
        },
        timeout=90,
    ).json()

if not result.get("success"):
    raise SystemExit(f"fill failed: {result}")

if result["missing_fields"]:
    print("not filled:", result["missing_fields"], "of", result["available_fields"])

# 4. Save the artifact locally
out = requests.get(f"{BASE}{result['downloadUrl']}", timeout=60)
out.raise_for_status()
open("vendor-intake-filled.pdf", "wb").write(out.content)
print("saved", result["size"], "bytes, flattened:", result["flattened"])

The missing_fields branch is the part worth keeping. In a batch run it converts a silent partial fill into a per-document warning you can route to a human, which matters far more than speed when the output is a contract.

Give an agent the same capability over MCP

The hosted MCP server at https://agentmediatools.com/api/mcp exposes this route as the tool pdf_form_fill. Its arguments are pdf_url (a public URL — MCP calls cannot upload a local file), fields (an object), and the optional flatten, stamp_text, and page_numbers flags.

Two boundaries to plan around:

Batch filling without losing track of documents

The endpoint takes one PDF and one map per request, which is the right unit for a pipeline: one row of a spreadsheet, one vendor record, one applicant. Two habits keep a folder-scale run debuggable.

Errors you will actually hit

SymptomCauseFix
count: 0 from list-fieldsFlat/scanned PDF or XFA formNo fields to fill; extract text or OCR instead
Key in missing_fieldsName mismatch or wrong value typeCompare against available_fields; check dropdown option strings
"fields must be valid JSON object"Unquoted or malformed JSON in the multipart fieldSerialize with json.dumps or JSON.stringify, never string concatenation
Remote file too largeurl input above the 5 MB fetch capUpload the file as multipart instead
Filled copy looks editableflatten not setSend flatten=true for delivery copies

One privacy note: filled documents are served from a temporary download path, so treat the link as public for its lifetime. For forms carrying tax IDs, health details, or addresses, that window is a real consideration — fetch the bytes promptly and avoid pasting download links into chat logs or issue trackers.

Where this fits

Form filling is the last mile of a document pipeline that usually starts with extraction. If you already pull data out of PDFs with the PDF processing endpoints, this closes the loop: read the fields, write the fields, flatten, deliver. The PDF form fill tool page runs the same request in a browser panel if you want to inspect a template by hand before automating it.

Try it in the Toolbox

Fill a form in the browser, or call the same endpoint from your agent with an API key and a daily free allowance.

Open toolbox