Skip to content

Fill in a form

The fill_form node (called Edit in the Studio) finds the blanks of a PDF form, matches them with your instructions and writes the values in, returning the filled PDF as a run artifact. Instructions it cannot place anywhere are reported back, not guessed.

The documents are synthetic (invented names, amounts and accounts), generated by scripts/docs_examples.py:

The graph

parse → fill

The full version body (graph and schemas), as the API takes it:

{
  "graph": {
    "nodes": [
      {
        "id": "parse",
        "type": "parse"
      },
      {
        "id": "fill",
        "type": "fill_form",
        "config": {
          "instructions": "Full name Ana Perez Garcia, ID 12345678Z, born 12/03/1985, address Calle Mayor 1. Tick the last box. Send a copy to accounting.",
          "output_mode": "flattened"
        }
      }
    ],
    "edges": [
      {
        "source": "parse",
        "target": "fill"
      }
    ]
  },
  "schemas": {}
}

Create it and run it

Set DX_BASE_URL and DX_API_KEY (see the quickstart), cd to docs/examples/gallery/fill-form/ and run any of the three. They do the same.

Python

# SPDX-License-Identifier: Apache-2.0
# expect: "status": "succeeded"
"""Fill in a form: create the workflow, run it on the document and print what comes back."""

import json
import os
import secrets
from pathlib import Path

import httpx

api = httpx.Client(
    base_url=os.environ["DX_BASE_URL"],
    headers={"Authorization": f"Bearer {os.environ['DX_API_KEY']}"},
    timeout=120,
)
name = f"fill-form-{secrets.token_hex(3)}"  # unique, so the example can run again

# 1. Create the workflow, add the version (graph + schemas), publish it, point `prod` at it.
workflow = api.post("/v1/workflows", json={"name": name}).raise_for_status().json()
version = (
    api.post(
        f"/v1/workflows/{workflow['id']}/versions",
        json=json.loads(Path("workflow.json").read_text()),
    )
    .raise_for_status()
    .json()
)
api.post(f"/v1/workflow-versions/{version['id']}:publish", json={}).raise_for_status()
api.put(
    f"/v1/workflows/{workflow['id']}/aliases/prod", json={"version_id": version["id"]}
).raise_for_status()

# 2. Run it on the form and wait for the run to finish.
run = (
    api.post(
        "/v1/runs",
        data={"workflow": f"{name}@prod"},
        files=[
            (
                "files",
                (
                    "registration-form.pdf",
                    Path("registration-form.pdf").read_bytes(),
                    "application/pdf",
                ),
            )
        ],
    )
    .raise_for_status()
    .json()
)
run = api.get(f"/v1/runs/{run['id']}", params={"wait": 60}).raise_for_status().json()

# 3. The node's result lists every blank; the filled PDF is an artifact of the run.
nodes = api.get(f"/v1/runs/{run['id']}/nodes").raise_for_status().json()["data"]
fill = next(n for n in nodes if n["node_id"] == "fill")
pdf = (
    api.get(f"/v1/runs/{run['id']}/artifacts/{fill['artifacts'][0]['id']}")
    .raise_for_status()
    .content
)

edit = fill["output_refs"]["edit"]
view = {
    "status": run["status"],
    "filled": [
        {"field": f["label"], "value": f["value"], "source": f["source"]}
        for f in edit["fields"]
        if f["value"] is not None
    ],
    "unmatched_instructions": edit["unmatched_instructions"],
    "pdf_downloaded": pdf[:5] == b"%PDF-",
}
print(json.dumps(view, indent=2))

TypeScript

// SPDX-License-Identifier: Apache-2.0
// expect: "status": "succeeded"
// Fill in a form: create the workflow, run it on the document and print what comes back.
// Node 22+: node --experimental-strip-types create.ts
import { readFileSync } from "node:fs";

const base = process.env.DX_BASE_URL as string;
const auth = { Authorization: `Bearer ${process.env.DX_API_KEY}` };
const name = `fill-form-${Math.random().toString(16).slice(2, 8)}`; // unique, so it can run again

async function call(path: string, init: RequestInit = {}): Promise<any> {
  const response = await fetch(base + path, { ...init, headers: { ...auth, ...init.headers } });
  if (!response.ok) throw new Error(`${response.status} ${path}: ${await response.text()}`);
  return response.json();
}
const json = (body: unknown): RequestInit => ({
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(body),
});

// 1. Create the workflow, add the version (graph + schemas), publish it, point `prod` at it.
const workflow = await call("/v1/workflows", json({ name }));
const version = await call(
  `/v1/workflows/${workflow.id}/versions`,
  json(JSON.parse(readFileSync("workflow.json", "utf8"))),
);
await call(`/v1/workflow-versions/${version.id}:publish`, json({}));
await call(`/v1/workflows/${workflow.id}/aliases/prod`, {
  ...json({ version_id: version.id }),
  method: "PUT",
});

// 2. Run it on the form and wait for the run to finish.
const form = new FormData();
form.append("workflow", `${name}@prod`);
form.append("files", new Blob([readFileSync("registration-form.pdf")], { type: "application/pdf" }), "registration-form.pdf");
const started = await call("/v1/runs", { method: "POST", body: form });
const run = await call(`/v1/runs/${started.id}?wait=60`);

// 3. The node's result lists every blank; the filled PDF is an artifact of the run.
const nodes = (await call(`/v1/runs/${run.id}/nodes`)).data;
const fill = nodes.find((n: any) => n.node_id === "fill");
const download = await fetch(`${base}/v1/runs/${run.id}/artifacts/${fill.artifacts[0].id}`, { headers: auth });
const pdf = Buffer.from(await download.arrayBuffer());

const edit = fill.output_refs.edit;
const view = {
  status: run.status,
  filled: edit.fields
    .filter((f: any) => f.value !== null)
    .map((f: any) => ({ field: f.label, value: f.value, source: f.source })),
  unmatched_instructions: edit.unmatched_instructions,
  pdf_downloaded: pdf.subarray(0, 5).toString() === "%PDF-",
};
console.log(JSON.stringify(view, null, 2));

curl

#!/usr/bin/env bash
# SPDX-License-Identifier: Apache-2.0
# expect: "status": "succeeded"
# Fill in a form: create the workflow, run it on the document and print what comes back.
# Needs curl and jq; DX_BASE_URL and DX_API_KEY in the environment.
set -euo pipefail
api() { curl -sS --fail-with-body -H "Authorization: Bearer $DX_API_KEY" "$@"; }
JSON='Content-Type: application/json'
NAME="fill-form-$RANDOM$RANDOM"  # unique, so the example can run again

# 1. Create the workflow, add the version (graph + schemas), publish it, point `prod` at it.
WORKFLOW=$(api -X POST "$DX_BASE_URL/v1/workflows" -H "$JSON" -d "{\"name\": \"$NAME\"}" | jq -r .id)
VERSION=$(api -X POST "$DX_BASE_URL/v1/workflows/$WORKFLOW/versions" -H "$JSON" -d @workflow.json | jq -r .id)
api -X POST "$DX_BASE_URL/v1/workflow-versions/$VERSION:publish" -H "$JSON" -d '{}' > /dev/null
api -X PUT "$DX_BASE_URL/v1/workflows/$WORKFLOW/aliases/prod" -H "$JSON" \
  -d "{\"version_id\": \"$VERSION\"}" > /dev/null

# 2. Run it on the form and wait for the run to finish.
RUN=$(api -X POST "$DX_BASE_URL/v1/runs" -F "workflow=$NAME@prod" -F "files=@registration-form.pdf" | jq -r .id)
STATUS=$(api "$DX_BASE_URL/v1/runs/$RUN?wait=60" | jq -r .status)

# 3. The node's result lists every blank; the filled PDF is an artifact of the run.
NODE=$(api "$DX_BASE_URL/v1/runs/$RUN/nodes" | jq -c '.data[] | select(.node_id == "fill")')
ARTIFACT=$(echo "$NODE" | jq -r '.artifacts[0].id')
MAGIC=$(api "$DX_BASE_URL/v1/runs/$RUN/artifacts/$ARTIFACT" | head -c 5)   # save it with: -o filled.pdf
echo "$NODE" | jq --arg status "$STATUS" --arg magic "$MAGIC" '{status: $status, filled: [.output_refs.edit.fields[] | select(.value != null) | {field: .label, value, source}], unmatched_instructions: .output_refs.edit.unmatched_instructions, pdf_downloaded: ($magic == "%PDF-")}'

Response

Produced by running the script above against a server with the fake model and these documents; make docs runs all the examples again and fails if an answer changes.

{
  "status": "succeeded",
  "filled": [
    {
      "field": "Nombre completo",
      "value": "Ana Perez Garcia",
      "source": "instruction"
    },
    {
      "field": "NIF",
      "value": "12345678Z",
      "source": "instruction"
    },
    {
      "field": "Fecha de nacimiento (dd/mm/aaaa)",
      "value": "12/03/1985",
      "source": "instruction"
    },
    {
      "field": "Direccion",
      "value": "Calle Mayor 1",
      "source": "instruction"
    },
    {
      "field": "Casado",
      "value": true,
      "source": "instruction"
    }
  ],
  "unmatched_instructions": [
    "Send a copy to accounting"
  ],
  "pdf_downloaded": true
}