> ## Documentation Index
> Fetch the complete documentation index at: https://docs.datalab.to/llms.txt
> Use this file to discover all available pages before exploring further.

# Form Fields

> Find the fillable fields on each page of a PDF or image with the Datalab SDK.

## Overview

`form_fields()` finds every fillable field on each page of a PDF or image: blank lines, empty boxes, tick boxes and signature blanks. Each field has a type, a box, the printed label next to it and, when the label does not say enough, a short descriptive name.

## Basic Usage

```python theme={null}
from datalab_sdk import DatalabClient

client = DatalabClient()

result = client.form_fields("form.pdf")

for page in result.pages:
    for field in page["fields"]:
        print(page["page"], field["field_type"], field["bbox"], field["label"])
```

## Form Fields Options

```python theme={null}
from datalab_sdk import FormFieldsOptions

options = FormFieldsOptions(page_range="0-2", skip_cache=True)
result = client.form_fields("form.pdf", options=options)
```

| Option | Type | Default | Description |
| - | - | - | - |
| `max_pages` | int | None | Maximum pages to process. Do not combine it with `page_range`. |
| `page_range` | str | None | Pages to process, for example `"0-2"` |
| `skip_cache` | bool | `False` | Skip cached results |
| `webhook_url` | str | None | URL that receives a call when the request completes |
| `processing_location` | str | None | Residency region, for example `"eu"` |
| `include_text` | bool | `False` | Also read the page text and mark each field in it. Slower, and billed as a fast mode parse plus form fields. |

## Form Fields Result

| Field | Type | Description |
| - | - | - |
| `success` | bool | Whether detection succeeded |
| `status` | str | Processing status |
| `pages` | list | One dict per page with `page`, `fields` and `error`, and `text` with `include_text` |
| `json` | dict | With `include_text`: the fast mode parse JSON, with an `<input data-field-index>` tag in the HTML of each block that holds a field |
| `text_error` | str | With `include_text`: set when the page text could not be read. The fields are still returned. |
| `page_count` | int | Number of pages processed |
| `runtime` | float | Processing time in seconds |
| `cost_breakdown` | dict | Cost details |

Each entry of `fields` has:

| Key | Description |
| - | - |
| `field_type` | One of `signature`, `initials`, `email`, `name`, `firstName`, `lastName`, `company`, `title`, `date`, `text`, `checkbox`, `radio` |
| `bbox` | `[x0, y0, x1, y1]` as fractions of the page width and height, origin at the top-left corner |
| `label` | The printed label, or an empty string |
| `name` | A short descriptive name in English, set mainly for fields whose printed label is empty or unclear. It is an empty string when the printed label is enough. |

A page with `error` set was not read, or the model repeated itself and its fields may be incomplete.

## Fields in the Page Text

```python theme={null}
result = client.form_fields("form.pdf", options=FormFieldsOptions(include_text=True))

print(result.pages[0]["text"])
# Name: [name: "Applicant name"]
# [ ] Individual/sole proprietor
```

A field shows as `[type: "name"]`, with its descriptive name, or its printed label when it has no name. A checkbox shows as `[ ]` and a radio button as `( )`. The `data-field-index` of an `<input>` tag in `result.json` is the position of the field in `pages[page]["fields"]`.

## Draw the Boxes

Multiply the fractions by the size of an image of the page, at any resolution. The SDK doesn't render PDF pages; this sample uses `pypdfium2` and Pillow (`pip install pypdfium2 pillow`). For an image input, open it with `Image.open()` instead.

```python theme={null}
import pypdfium2 as pdfium
from PIL import ImageDraw

# Render page 1 of the PDF that result came from
image = pdfium.PdfDocument("form.pdf")[0].render(scale=2).to_pil()
draw = ImageDraw.Draw(image)
width, height = image.size

for field in result.pages[0]["fields"]:
    x0, y0, x1, y1 = field["bbox"]
    draw.rectangle([x0 * width, y0 * height, x1 * width, y1 * height], outline="red", width=2)

image.save("page_fields.png")
```

## Saving the Result

```python theme={null}
result.save_output("output/form")  # writes output/form.form_fields.json
```

## From URL

```python theme={null}
result = client.form_fields(file_url="https://example.com/form.pdf")
```

## Async Usage

```python theme={null}
import asyncio
from datalab_sdk import AsyncDatalabClient

async def find_fields():
    async with AsyncDatalabClient() as client:
        result = await client.form_fields("form.pdf")
        return result.pages

asyncio.run(find_fields())
```

## CLI

```bash theme={null}
datalab form-fields form.pdf --output_dir output
```

The command takes a file or a folder, and the same `--page_range`, `--max_pages` and `--skip_cache` options as the other commands. Add `--include_text` to get the page text with the fields marked.

## Next Steps

> [card] [Form Fields Recipe](https://docs.datalab.to/docs/recipes/form-fields/form-fields-api-overview.md)
>
> The API, the response format and the options.

> [card] [Form Filling SDK](https://docs.datalab.to/docs/welcome/sdk/form-filling.md)
>
> Fill the fields you found.

> [card] [CLI](https://docs.datalab.to/docs/welcome/sdk/cli.md)
>
> Process files and folders from the command line.

> [card] [File Management](https://docs.datalab.to/docs/welcome/sdk/file-management.md)
>
> Upload, list, and manage files in Datalab storage.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.