# OCR - PDF to Text

> Extract text from PDF documents using OCR (Optical Character Recognition).

Source: https://docs.sommatic.ai/en/nodes/ai.ocr/

- Slug: `ai.ocr`
- Family: AI
- Version: 1.0.0
- Status: Available
- Execution: async

Extract text from PDF documents using OCR (Optical Character Recognition).

Automatically detects whether the PDF contains embedded text or is a scanned image, and uses the optimal extraction method.

**Operations:**
- **Auto:** Try text extraction first (pdftotext), fall back to OCR if text is sparse.
- **Text Extract:** Fast extraction of embedded text only (no OCR). Best for digital PDFs.
- **OCR Only:** Force OCR on all pages. Best for scanned documents.

## Configuration

- `mode` (string, optional): Auto tries pdftotext first, falls back to OCR. Text Extract is fast for digital PDFs. OCR Only forces image-based recognition. Default: `auto`. Allowed values: `auto`, `text_extract`, `ocr_only`.
- `language` (string, optional): Tesseract language code (e.g., spa, eng, fra, deu, por). Default: `spa`.
- `dpi` (number, optional): Resolution for PDF-to-image conversion. Higher = better quality but slower. Default: `300`.
- `page_range` (string, optional, accepts expressions): Optional: process specific pages (e.g., "1-50"). Leave empty for all pages.

Its configuration shows the shared execution settings, but this node does not apply retries (`retryOnFail`, `maxTries`) yet. `continueOnFail` is not applied by any node.

## Output ports

- `extracted` (default): Text successfully extracted.
- `empty`: File exists but no meaningful text could be extracted.
- `error`: OCR processing failed.

## Input contract

- `content_base64` (string, optional): File content encoded as base64 string.
- `file_path` (string, optional): Alternative: local file path to the PDF or image.
- `content_type` (string, optional): MIME type (application/pdf, image/png, image/jpeg, ...). Optional but helps the router.

## Output contract

- `text` (string, optional): Extracted text with page markers.
- `pages` (number, optional): Total pages processed.
- `method` (string, optional): Extraction method used (pdftotext or ocr).
- `chars` (number, optional): Total character count.
- `empty` (boolean, optional): True when no meaningful text was extracted.

## In expressions

What a later node can read from this node's output with `$("OCR - PDF to Text").item.json.<path>` (write your node's label instead of `OCR - PDF to Text`). **Editor** marks the paths the workflow editor suggests under Previous Nodes (the output contract); **Worker** marks the paths the worker really returns through `extracted`, from the output shown in Ports.

- `$("OCR - PDF to Text").item.json.text` (string) = `"--- PAGE 1 ---\nINVOICE 2026-118\nCustomer: …"`: Extracted text with page markers.
- `$("OCR - PDF to Text").item.json.pages` (number) = `2`: Total pages processed.
- `$("OCR - PDF to Text").item.json.method` (string) = `"ocr"`: Extraction method used (pdftotext or ocr).
- `$("OCR - PDF to Text").item.json.chars` (number) = `90`: Total character count.
- `$("OCR - PDF to Text").item.json.empty` (boolean) = `false`: True when no meaningful text was extracted.


## How it works

Extracts text from a PDF or an image. PDFs go through `pdftotext` (Poppler) and/or Tesseract OCR depending on `mode`; images always go through Tesseract.

1. Resolves the node config: expressions in config keys are evaluated against the run; the incoming item is used as-is.
2. Reads `content_base64`, `file_path` and `content_type` from the config first, then from the incoming item. Without `content_base64` or `file_path` it returns `error`; a `file_path` that does not exist returns `File not found: <path>`.
3. Treats the input as an image when `content_type` starts with `image/` or `file_path` ends in .png, .jpg, .jpeg, .tif, .tiff, .bmp or .webp. Images are OCR-ed as a single page, whatever `mode` says.
4. For PDFs: `text_extract` runs `pdftotext -layout`; `ocr_only` renders pages at `dpi` and runs Tesseract with `language`; `auto` runs `pdftotext` and falls back to OCR when the average is 50 characters per page or fewer.
5. PDF text is joined with a `--- PAGE n ---` marker before each page. `method` says which path produced the result: `pdftotext` or `ocr`.
6. Returns `extracted` when `chars > 0` and `empty` is false, otherwise `empty`. Any failure (pdftotext or Python) returns `error` with `{ error }`.

## In a workflow

### Node

```json
{
  "node_id": "node-ocr",
  "label": "OCR document",
  "operator_slug": "ai.ocr",
  "operator_version": "1.0.0",
  "config": {
    "mode": "auto",
    "language": "eng",
    "dpi": 300,
    "page_range": "1-10",
    "execution": {
      "timeout_ms": 300000
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "extracted",
  "data": {
    "text": "--- PAGE 1 ---\nINVOICE 2026-118\nCustomer: Example Corp\n\n--- PAGE 2 ---\nTotal due: 3,400.00",
    "pages": 2,
    "method": "ocr",
    "chars": 90,
    "empty": false
  }
}
```

## Output ports (behaviour in the code)

### `extracted`

Text was found.

```json
{
  "text": "--- PAGE 1 ---\nINVOICE 2026-118\nCustomer: Example Corp\n\n--- PAGE 2 ---\nTotal due: 3,400.00",
  "pages": 2,
  "method": "ocr",
  "chars": 90,
  "empty": false
}
```

### `empty`

The selected path produced no text. Same shape with `empty: true`.

```json
{
  "text": "",
  "pages": 0,
  "method": "pdftotext",
  "chars": 0,
  "empty": true
}
```

### `error`

Missing input, missing file or any extraction failure.

```json
{
  "error": "pdftotext failed: Command failed: pdftotext -layout …"
}
```

## Behaviour in the code

- `mode`: Applies to PDFs only. Images are always OCR-ed.
- `page_range`: Only the `N-M` form is applied, both by `pdftotext` and by OCR. Any other value processes all pages.
- `language`: Tesseract language code, default `spa`. It does not affect `pdftotext`.
- `content_type`: Not declared in the config schema; read from the config or the incoming item. Set it (e.g. `image/png`) when you send an image as `content_base64`: without it the bytes are treated as a PDF.
- `execution.timeout_ms`: Default 300000 ms. In `auto` mode it applies separately to `pdftotext` and to the OCR step, so the node can take up to twice the value.
- `content_base64 / file_path`: Not declared in the config schema, but read from the config before the incoming item. Use them to point at a file with an expression, e.g. `{{ $json.attachment.content_base64 }}`.

## Errors

| Message | Port | Cause and fix |
| --- | --- | --- |
| `Either content_base64 or file_path is required.` | `error` | Neither the config nor the incoming item has `content_base64` or `file_path`. Map the file from the previous node. |
| `File not found: <file_path>` | `error` | `file_path` does not exist on the orchestrator host. |
| `pdftotext failed: <message>` | `error` | Poppler is not installed, the file is not a valid PDF (for example, a base64 image sent without `content_type`), or the run exceeded the timeout. |
| `<Tesseract or pdf2image error>` | `error` | Tesseract or the `language` data pack is not installed on the host, or the PDF cannot be rendered. |
| `Python timed out after <timeout_ms>ms` | `error` | The script exceeded `execution.timeout_ms`. Raise it or process fewer pages. |

## Notes and limits

- Requires `pdftotext` (Poppler) and Tesseract with the language data for `language` on the orchestrator host.
- With `pdftotext`, blank pages are dropped and the remaining pages are numbered 1, 2, 3…, so page markers can differ from the real page numbers. `pages` counts non-blank pages.
- OCR output keeps a marker per rendered page, so a scanned PDF where Tesseract reads nothing still goes out through `extracted` with markers only. Image results have no markers.
- For a single engine with no preprocessing, this node is enough; for skewed or noisy scans use `ai.ocr.adaptive`.
- The extraction runs in a Python subprocess. On first use the orchestrator creates a virtual environment and installs the pinned requirements, which can take minutes; later runs reuse it.
- The engine does not apply `execution.retryOnFail`, `maxTries`, `waitBetweenTries` or `continueOnFail` to this node. Handle failures by wiring the `error` port.


## Contracts (JSON Schema)

### All (`*.definition.js`)

```json
{
  "slug": "ai.ocr",
  "name": "OCR - PDF to Text",
  "category": "ai",
  "version": "1.0.0",
  "description": "Extract text from PDF documents using OCR (Optical Character Recognition).\n\n  Automatically detects whether the PDF contains embedded text or is a scanned image, and uses the optimal extraction method.\n\n  **Operations:**\n  - **Auto:** Try text extraction first (pdftotext), fall back to OCR if text is sparse.\n  - **Text Extract:** Fast extraction of embedded text only (no OCR). Best for digital PDFs.\n  - **OCR Only:** Force OCR on all pages. Best for scanned documents.",
  "capabilities": [
    "ocr",
    "pdf",
    "text-extraction",
    "document"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "mode": {
        "type": "string",
        "title": "Extraction Mode",
        "enum": [
          "auto",
          "text_extract",
          "ocr_only"
        ],
        "default": "auto",
        "description": "Auto tries pdftotext first, falls back to OCR. Text Extract is fast for digital PDFs. OCR Only forces image-based recognition."
      },
      "language": {
        "type": "string",
        "title": "OCR Language",
        "default": "spa",
        "description": "Tesseract language code (e.g., spa, eng, fra, deu, por)."
      },
      "dpi": {
        "type": "number",
        "title": "DPI",
        "default": 300,
        "description": "Resolution for PDF-to-image conversion. Higher = better quality but slower."
      },
      "page_range": {
        "type": "string",
        "title": "Page Range",
        "description": "Optional: process specific pages (e.g., \"1-50\"). Leave empty for all pages.",
        "format": "expression"
      },
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "content_base64": {
        "type": "string",
        "description": "File content encoded as base64 string."
      },
      "file_path": {
        "type": "string",
        "description": "Alternative: local file path to the PDF or image."
      },
      "content_type": {
        "type": "string",
        "description": "MIME type (application/pdf, image/png, image/jpeg, ...). Optional but helps the router."
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string",
        "description": "Extracted text with page markers."
      },
      "pages": {
        "type": "number",
        "description": "Total pages processed."
      },
      "method": {
        "type": "string",
        "description": "Extraction method used (pdftotext or ocr)."
      },
      "chars": {
        "type": "number",
        "description": "Total character count."
      },
      "empty": {
        "type": "boolean",
        "description": "True when no meaningful text was extracted."
      }
    }
  },
  "ports": [
    {
      "port_id": "extracted",
      "label": "Text Extracted",
      "description": "Text successfully extracted.",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "empty",
      "label": "No Text",
      "description": "File exists but no meaningful text could be extracted.",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "OCR processing failed.",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "ocr",
    "pdf",
    "image",
    "text",
    "document"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "mode": {
      "type": "string",
      "title": "Extraction Mode",
      "enum": [
        "auto",
        "text_extract",
        "ocr_only"
      ],
      "default": "auto",
      "description": "Auto tries pdftotext first, falls back to OCR. Text Extract is fast for digital PDFs. OCR Only forces image-based recognition."
    },
    "language": {
      "type": "string",
      "title": "OCR Language",
      "default": "spa",
      "description": "Tesseract language code (e.g., spa, eng, fra, deu, por)."
    },
    "dpi": {
      "type": "number",
      "title": "DPI",
      "default": 300,
      "description": "Resolution for PDF-to-image conversion. Higher = better quality but slower."
    },
    "page_range": {
      "type": "string",
      "title": "Page Range",
      "description": "Optional: process specific pages (e.g., \"1-50\"). Leave empty for all pages.",
      "format": "expression"
    },
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "content_base64": {
      "type": "string",
      "description": "File content encoded as base64 string."
    },
    "file_path": {
      "type": "string",
      "description": "Alternative: local file path to the PDF or image."
    },
    "content_type": {
      "type": "string",
      "description": "MIME type (application/pdf, image/png, image/jpeg, ...). Optional but helps the router."
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string",
      "description": "Extracted text with page markers."
    },
    "pages": {
      "type": "number",
      "description": "Total pages processed."
    },
    "method": {
      "type": "string",
      "description": "Extraction method used (pdftotext or ocr)."
    },
    "chars": {
      "type": "number",
      "description": "Total character count."
    },
    "empty": {
      "type": "boolean",
      "description": "True when no meaningful text was extracted."
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "extracted",
    "label": "Text Extracted",
    "description": "Text successfully extracted.",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "empty",
    "label": "No Text",
    "description": "File exists but no meaningful text could be extracted.",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "OCR processing failed.",
    "is_default": false,
    "supports_condition": false
  }
]
```
