# PDF Text Extraction

> Extracts the embedded text layer from PDF documents using PyMuPDF.

Source: https://docs.sommatic.ai/en/nodes/ai.pdf.extract.text/

- Slug: `ai.pdf.extract.text`
- Family: AI
- Version: 1.0.0
- Status: Available
- Execution: async

Extracts the embedded text layer from PDF documents using PyMuPDF.

Reads the native text stream of a PDF without rasterization or OCR, preserving the document's logical reading order and emitting page-level markers in the output.

**Operational notes:**
- **Text layer only:** Returns the PDF's embedded text. Scanned PDFs and image-based PDFs have no text layer and will emit port `empty`.
- **Page range:** Optional filter to process a subset of pages (e.g. `1-50`, `1,5,10-20`).
- **Metadata:** Returns page count, character count, and document metadata (title, author, producer) when present.
- **Downstream fallback:** For scanned PDFs, route `empty` output to `ai.ocr` or `ai.ocr.adaptive`.

## Configuration

- `page_range` (string, optional, accepts expressions): Optional: process specific pages (e.g., "1-50").

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): Extracted
- `empty`: No Text Layer
- `error`: Error

## Input contract

- `content_base64` (string, optional)
- `file_path` (string, optional)

## Output contract

- `text` (string, optional)
- `chars` (number, optional)
- `empty` (boolean, optional)
- `method` (string, optional)
- `metadata` (object, optional)

## In expressions

What a later node can read from this node's output with `$("PDF Text Extraction").item.json.<path>` (write your node's label instead of `PDF Text Extraction`). **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.

- `$("PDF Text Extraction").item.json.text` (string) = `"--- PAGE 1 ---\nPurchase order 4471\nTotal: …"`
- `$("PDF Text Extraction").item.json.chars` (number) = `87`
- `$("PDF Text Extraction").item.json.empty` (boolean) = `false`
- `$("PDF Text Extraction").item.json.method` (string) = `"pymupdf_text_layer"`
- `$("PDF Text Extraction").item.json.metadata` (object) = `{…}`
- `$("PDF Text Extraction").item.json.metadata.total_pages` (number) = `2` (Not suggested by the editor)
- `$("PDF Text Extraction").item.json.metadata.pages_processed` (number) = `2` (Not suggested by the editor)
- `$("PDF Text Extraction").item.json.metadata.pages_with_text` (number) = `2` (Not suggested by the editor)
- `$("PDF Text Extraction").item.json.metadata.has_text_layer` (boolean) = `true` (Not suggested by the editor)


## How it works

Reads the embedded text layer of a PDF with PyMuPDF, page by page, without OCR. A PDF with no text on any page goes out through `empty` so you can route it to OCR.

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` or `file_path` from the config first, then from the incoming item. If neither is present it returns `error`.
3. Runs the Python script with `content_base64`, `file_path` and `page_range`; it opens the PDF from the base64 bytes or from the path.
4. Extracts the text of each page in the range and joins the pages with a `--- PAGE n ---` marker before each one.
5. Sets `empty: true` when no page has text, and returns counts in `metadata`.
6. If the script fails it returns `error` with the Python message and stderr. Otherwise `empty: true` goes out through `empty` and any other result through `extracted`.

## In a workflow

### Node

```json
{
  "node_id": "node-pdf-text",
  "label": "Read PDF text",
  "operator_slug": "ai.pdf.extract.text",
  "operator_version": "1.0.0",
  "config": {
    "page_range": "1-20",
    "execution": {
      "timeout_ms": 120000
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "extracted",
  "data": {
    "text": "--- PAGE 1 ---\nPurchase order 4471\nTotal: 1,250.00\n\n--- PAGE 2 ---\nTerms and conditions",
    "chars": 87,
    "empty": false,
    "method": "pymupdf_text_layer",
    "metadata": {
      "total_pages": 2,
      "pages_processed": 2,
      "pages_with_text": 2,
      "has_text_layer": true
    }
  }
}
```

## Output ports (behaviour in the code)

### `extracted`

At least one page in the range has text.

```json
{
  "text": "--- PAGE 1 ---\nPurchase order 4471\nTotal: 1,250.00\n\n--- PAGE 2 ---\nTerms and conditions",
  "chars": 87,
  "empty": false,
  "method": "pymupdf_text_layer",
  "metadata": {
    "total_pages": 2,
    "pages_processed": 2,
    "pages_with_text": 2,
    "has_text_layer": true
  }
}
```

### `empty`

No page in the range has text (typically a scanned PDF). The shape is the same, with `empty: true`; `text` still holds the page markers.

```json
{
  "text": "--- PAGE 1 ---\n\n\n--- PAGE 2 ---",
  "chars": 31,
  "empty": true,
  "method": "pymupdf_text_layer",
  "metadata": {
    "total_pages": 2,
    "pages_processed": 2,
    "pages_with_text": 0,
    "has_text_layer": false
  }
}
```

### `error`

The input is missing or the script fails. `data` is `{ error }` or `{ error, stderr }`.

```json
{
  "error": "Python timed out after 120000ms",
  "stderr": ""
}
```

## Behaviour in the code

- `page_range`: Only the `N-M` form is applied (1-based, inclusive; the end is clamped to the last page). Any other value, such as `7` or `1,5,10-20`, processes all pages.
- `execution.timeout_ms`: Timeout of the Python subprocess. When unset the code uses 120000 ms (the schema shows 300000 as the default).
- `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. |
| `Either content_base64 or file_path is required` | `error` | Raised by the Python script when `file_path` does not exist on the orchestrator host. Data also carries `stderr`. |
| `<exception message from the Python library>` | `error` | The file could not be read as a PDF (corrupt, encrypted or another format). `data.stderr` has the details. |
| `Python timed out after <timeout_ms>ms` | `error` | The script exceeded `execution.timeout_ms`. Raise it or process fewer pages. |
| `Python runtime not available (ENOENT)` | `error` | No Python interpreter is available on the orchestrator host. |

## Notes and limits

- No OCR: scanned or image-only pages produce no text. Route `empty` to `ai.ocr` or `ai.ocr.adaptive`.
- `chars` counts the whole `text`, page markers included.
- The description mentions document metadata (title, author, producer); the code does not return it. `metadata` only has page counts.
- `file_path` is a path on the orchestrator host. `content_base64` wins when both are present.
- 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 Python result is limited to 50 MB of output; above it the node leaves through `error`.
- 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.pdf.extract.text",
  "name": "PDF Text Extraction",
  "category": "ai",
  "version": "1.0.0",
  "description": "Extracts the embedded text layer from PDF documents using PyMuPDF.\n\n  Reads the native text stream of a PDF without rasterization or OCR, preserving the document's logical reading order and emitting page-level markers in the output.\n\n  **Operational notes:**\n  - **Text layer only:** Returns the PDF's embedded text. Scanned PDFs and image-based PDFs have no text layer and will emit port `empty`.\n  - **Page range:** Optional filter to process a subset of pages (e.g. `1-50`, `1,5,10-20`).\n  - **Metadata:** Returns page count, character count, and document metadata (title, author, producer) when present.\n  - **Downstream fallback:** For scanned PDFs, route `empty` output to `ai.ocr` or `ai.ocr.adaptive`.",
  "capabilities": [
    "pdf",
    "text-extraction",
    "document"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "page_range": {
        "type": "string",
        "title": "Page Range",
        "format": "expression",
        "description": "Optional: process specific pages (e.g., \"1-50\")."
      },
      "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"
      },
      "file_path": {
        "type": "string"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string"
      },
      "chars": {
        "type": "number"
      },
      "empty": {
        "type": "boolean"
      },
      "method": {
        "type": "string"
      },
      "metadata": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "extracted",
      "label": "Extracted",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "empty",
      "label": "No Text Layer",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "pdf",
    "text"
  ],
  "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": {
    "page_range": {
      "type": "string",
      "title": "Page Range",
      "format": "expression",
      "description": "Optional: process specific pages (e.g., \"1-50\")."
    },
    "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"
    },
    "file_path": {
      "type": "string"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string"
    },
    "chars": {
      "type": "number"
    },
    "empty": {
      "type": "boolean"
    },
    "method": {
      "type": "string"
    },
    "metadata": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "extracted",
    "label": "Extracted",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "empty",
    "label": "No Text Layer",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "is_default": false,
    "supports_condition": false
  }
]
```
