# PDF Table to JSON + MCP: Merged Cells & Multi-Page Tables (`hgreene624/pdf-table-json`) Actor

Deterministic zero-LLM PDF table extractor reconstructing colspan/rowspan merged cells, stitching multi-page continuation tables, and outputting structured JSON, Markdown, and CSV via Batch or warm MCP Server.

- **URL**: https://apify.com/hgreene624/pdf-table-json.md
- **Developed by:** [Holden Greene](https://apify.com/hgreene624) (community)
- **Categories:** Developer tools, AI, MCP servers
- **Features:** Limited permissions, Single-tenant, Server interface
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.60 / 1,000 digital pdf page extracteds

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## PDF Table & Document to JSON + MCP — Merged Cells & Multi-Page Stitching

Extract accurate, zero-LLM structured tables from digital PDFs in seconds without hallucinated numbers or broken columns. Reconstructs merged header and body cells, stitches tables that continue across pages, and outputs clean JSON records, reading-order Markdown, RAG sections, and spreadsheet-safe CSV.

Works in **Batch Mode** (CSV, Excel, JSON, n8n, Make, Zapier) and as a **live MCP server** for Claude, Cursor, ChatGPT, and autonomous AI agents.

> **Free Plan Preview:** Free Apify accounts process up to 5 PDFs, 25 total digital pages, and 10 MB per PDF per batch run, and 5 MCP calls per 24 hours (up to 25 pages and 10 MB per call). Any paid Apify plan unlocks up to 250 PDFs per batch, 500 pages per PDF, and 50 MB files.

![PDF Table & Document to JSON + MCP Architecture](https://hgreene624.github.io/studio-docs/assets/apify/banners/pdf-table-json-architecture.png)

### Why teams use this Actor

- **Zero hallucinations on financial and operational tables:** Uses deterministic document geometry instead of vision LLMs so every number, currency figure, and row stays faithful to the source PDF.
- **Full merged-cell reconstruction:** Rebuilds horizontal and vertical merged cells, flattens multi-row spanning headers cleanly, and expands covered cells for spreadsheets and databases.
- **Smart multi-page table stitching:** Joins tables that continue across pages, removes repeated headers, repairs split rows, and avoids falsely merging separate financial statements.
- **Works on bordered and borderless layouts:** Extracts ruled invoices, shaded financial schedules, academic tables, and borderless reports while ignoring two-column prose.
- **Private files and encrypted PDFs supported:** Accepts public URLs or private Base64 uploads directly with optional password unlocking that never logs secrets.

### What data do you get?

| Category | Fields Included |
|---|---|
| **Structured tables** | Clean column headers, row arrays, key-value JSON records, merged-cell span metadata, and extraction confidence score |
| **Multi-page stitching** | Combined page range, stitched table indicator, and count of deduplicated repeated headers |
| **Document Markdown** | Full reading-order Markdown combining headings, body prose, and formatted tables for LLM context |
| **RAG sections** | Chunked document sections split by heading hierarchy with page numbers for retrieval pipelines |
| **Spreadsheet-ready CSV** | Optional formula-safe CSV per table ready for Excel, Google Sheets, Airtable, or SQL imports |
| **Document metadata** | Page count, digital vs. scanned page classification, file name, and optional Key-Value Store spill link for very large outputs |

### Pricing

Simple Pay-Per-Event billing with volume discounts up to 60% off on higher Apify plans. You pay **$0 per scanned image-only page**.

| Mode / Event | Price | Per 1,000 | Best For |
|---|---:|---:|---|
| **PDF Document Processed** (`pdf-document-processed`) | $0.005 / PDF | $5 | Per PDF opened in Batch mode, or quick MCP metadata preflight |
| **Digital Page Extracted** (`pdf-page-extracted`) | $0.001 / page | $1 | Per digital text page extracted across Batch and MCP ($0 on scanned pages) |
| **Real-Time MCP / REST Call** (`mcp-extract-call`) | $0.010 / call | $10 | Base fee for warm Standby MCP or REST single-PDF extraction |
| **Batch Run Start** (`apify-actor-start`) | $0.005 / run | — | One-time batch start fee (amortized across all PDFs in a Batch run) |

Example: 100 single-page invoices cost **$0.605** in one Batch run (one-time start fee amortized) vs. **$1.100** across 100 real-time MCP or REST calls.

### Quick Start

Test immediately with the bundled 2-page financial sample, or pass your own public PDF URLs or Base64 files:

```json
{
  "urls": ["https://example.com/quarterly-report.pdf"],
  "useBundledSample": false,
  "tableStrategy": "auto",
  "stitchMultipageTables": true,
  "parseNumbers": true,
  "includeCsv": true
}
```

<details>
<summary>View sample JSON output</summary>

```json
{
  "file_name": "sample_quarterly_report.pdf",
  "document_type": "digital",
  "table_count": 2,
  "stitched_table_count": 1,
  "tables": [
    {
      "table_id": "t_001",
      "caption": "Table 1: Quarterly Revenue by Region ($M)",
      "page_range": [1, 1],
      "headers": ["Region", "Segment", "FY 2026 > Q1", "FY 2026 > Q2"],
      "records": [
        {"Region": "North America", "Segment": "Enterprise", "FY 2026 > Q1": "$42.1", "FY 2026 > Q2": "$48.5"}
      ]
    }
  ]
}
```

</details>

### Connect to AI Agents (MCP), n8n, Make, or Python

#### Cursor, Claude Code, and Windsurf (MCP)

```json
{
  "mcpServers": {
    "pdf-table-json": {
      "type": "streamable-http",
      "url": "https://hgreene624--pdf-table-json.apify.actor/mcp",
      "headers": {
        "Authorization": "Bearer <YOUR_APIFY_TOKEN>"
      }
    }
  }
}
```

Available MCP tools: `extract_pdf_tables`, `extract_pdf_document`, and `inspect_pdf_metadata`.

<details>
<summary>Claude Desktop, Apify MCP Gateway, n8n, and Python examples</summary>

**Claude Desktop (local config via mcp-remote):**

```json
{
  "mcpServers": {
    "pdf-table-json": {
      "command": "npx",
      "args": [
        "-y",
        "mcp-remote",
        "https://hgreene624--pdf-table-json.apify.actor/mcp",
        "--header",
        "Authorization: Bearer <YOUR_APIFY_TOKEN>"
      ]
    }
  }
}
```

**Hosted Apify MCP Gateway:** `https://mcp.apify.com?tools=hgreene624/pdf-table-json`

**Direct Standby REST API (n8n, Make, Zapier):**
`POST https://hgreene624--pdf-table-json.apify.actor/v1/extract`

**Python SDK:**

```python
from apify_client import ApifyClient

client = ApifyClient("<YOUR_APIFY_TOKEN>")
run = client.actor("hgreene624/pdf-table-json").call(
    run_input={"urls": ["https://example.com/quarterly-report.pdf"], "stitchMultipageTables": True, "includeCsv": True},
    max_total_charge_usd=0.25,
)
items = list(client.dataset(run["defaultDatasetId"]).iterate_items())
```

</details>

### FAQ

**What happens if I upload a scanned image-only PDF?**
Scanned pages are detected automatically, flagged with a clear notice, and billed $0 for page extraction so you never pay per-page fees for image-only scans.

**How do I process private or password-protected PDFs without hosting them publicly?**
Send Base64-encoded PDF payloads directly via `base64Pdfs` in Batch mode or `base64_pdf` in MCP and REST calls, with an optional secret `pdfPassword` unlocked strictly in memory.

**Can I check a PDF's page count and estimated cost before extracting it via MCP?**
Yes. Call `inspect_pdf_metadata` ($0.005 flat) first to see total pages, encryption status, scanned-page ratio, and estimated cost while warming the file cache for instant extraction.

**How does Batch mode differ from Standby MCP or REST pricing?**
On the Free tier, a single PDF costs the exact same in Batch or MCP ($0.011 for 1 page). For folders of multiple PDFs, Batch mode charges the $0.005 start fee only once across the whole batch.

# Actor input Schema

## `urls` (type: `array`):

Direct public http(s) PDF URLs to extract (max 250 paid / 5 Free plan preview cap). Protected against SSRF and private IP ranges.

## `base64Pdfs` (type: `array`):

Private PDF files supplied as base64 strings or {"fileName": "invoice.pdf", "data": "..."} objects (zero external URL hosting needed).

## `useBundledSample` (type: `boolean`):

When urls and base64Pdfs are both empty, setting this explicitly to true runs the built-in 2-page quarterly financial sample (with merged cells and a multi-page stitched table). Defaults to false so API/agent calls with missing URLs fail cleanly instead of returning demo data.

## `pdfPassword` (type: `string`):

Optional password for encrypted PDFs (never logged or echoed in output).

## `pageRange` (type: `string`):

Optional 1-indexed pages or ranges, e.g. '1-5,10,12-15'. Leave empty to extract all pages up to maxPagesPerPdf.

## `tableStrategy` (type: `string`):

auto (recommended default: detects both bordered and borderless tables), lattice (bordered/ruled tables only), stream (borderless whitespace-aligned tables only), or hybrid (alias for auto running both bordered and borderless detection).

## `stitchMultipageTables` (type: `boolean`):

Automatically stitch tables continuing across consecutive pages, deduplicate repeated headers, and emit unified page_range.

## `fillMergedCells` (type: `string`):

Controls WHICH merged spans are detected: lattice_only (recommended: expand only cells with explicit ruled borders), never (skip vertical body-cell span expansion), or aggressive (also infer grouped labels in the leftmost text column, stopping at total rows).

## `mergedCellMode` (type: `string`):

Controls HOW detected merged cells are written into rows\[] and records\[]: 'repeat' copies the label into every covered cell (best for CSV/Sheets/SQL); 'first_only' places the label only in the top-left cell and leaves covered cells empty.

## `headerSeparator` (type: `string`):

Separator used when flattening multi-row spanning headers (e.g. 'FY 2026 > Q1').

## `parseNumbers` (type: `boolean`):

Opt-in column-level Decimal parser returning {value, raw, unit, locale} objects while preserving leading zeros, >2^53 IDs, dates, and % units.

## `minConfidence` (type: `number`):

Minimum confidence threshold (0.0-1.0) required to accept a detected table.

## `includeMarkdown` (type: `boolean`):

Include full reading-order document Markdown with inline tables.

## `includeSections` (type: `boolean`):

Include heading-grouped sections\[] for downstream RAG chunking.

## `markdownTableFormat` (type: `string`):

gfm (GitHub-Flavored Markdown pipe tables), html (lossless colspan/rowspan <table>), or auto_html_on_merge.

## `includeCsv` (type: `boolean`):

Include RFC-4180 formula-sanitized CSV string on each table object.

## `sanitizeCsvFormulas` (type: `boolean`):

Neutralize leading formula injection triggers (=, +, -, @, |, %) line-by-line in CSV outputs.

## `includeRawGrid` (type: `boolean`):

Optional extra field: attach raw_grid alongside rows\[] with null in covered merged-cell slots (for custom post-processing). Off by default to keep payloads smaller.

## `stripRunningHeadersFooters` (type: `boolean`):

Strip repeating top/bottom 8% running headers and footers (e.g. 'Page 2 of 10') on >=3-page documents.

## `normalizeUnicode` (type: `string`):

ligatures_only (recommended default: fixes PDF typographic ligatures like 'fi' and 'fl' without altering superscripts or fractions) or nfkc (full Unicode compatibility normalization).

## `maxPagesPerPdf` (type: `integer`):

Maximum pages extracted per PDF (paid hard cap 500; Free plan preview cap 25 total pages per run).

## `maxFileSizeMb` (type: `integer`):

Maximum PDF file size in MB. Console prefill is 10 MB to match the Apify Free plan cap; paid plans support up to 50 MB (API default: 25 MB).

## `timeoutPerPdfSecs` (type: `integer`):

Wall-clock timeout per isolated PDF worker process (5-180s).

## Actor input object example

```json
{
  "urls": [],
  "base64Pdfs": [],
  "useBundledSample": true,
  "pageRange": "",
  "tableStrategy": "auto",
  "stitchMultipageTables": true,
  "fillMergedCells": "lattice_only",
  "mergedCellMode": "repeat",
  "headerSeparator": " > ",
  "parseNumbers": false,
  "minConfidence": 0.35,
  "includeMarkdown": true,
  "includeSections": true,
  "markdownTableFormat": "gfm",
  "includeCsv": false,
  "sanitizeCsvFormulas": true,
  "includeRawGrid": false,
  "stripRunningHeadersFooters": true,
  "normalizeUnicode": "ligatures_only",
  "maxPagesPerPdf": 25,
  "maxFileSizeMb": 10,
  "timeoutPerPdfSecs": 30
}
```

# Actor output Schema

## `results` (type: `string`):

No description

## `mcpEndpoint` (type: `string`):

No description

## `restExtractEndpoint` (type: `string`):

No description

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "urls": [],
    "base64Pdfs": [],
    "useBundledSample": true,
    "pageRange": "",
    "tableStrategy": "auto",
    "stitchMultipageTables": true,
    "fillMergedCells": "lattice_only",
    "mergedCellMode": "repeat",
    "headerSeparator": " > ",
    "parseNumbers": false,
    "minConfidence": 0.35,
    "includeMarkdown": true,
    "includeSections": true,
    "markdownTableFormat": "gfm",
    "includeCsv": false,
    "sanitizeCsvFormulas": true,
    "includeRawGrid": false,
    "stripRunningHeadersFooters": true,
    "normalizeUnicode": "ligatures_only",
    "maxPagesPerPdf": 25,
    "maxFileSizeMb": 10,
    "timeoutPerPdfSecs": 30
};

// Run the Actor and wait for it to finish
const run = await client.actor("hgreene624/pdf-table-json").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "urls": [],
    "base64Pdfs": [],
    "useBundledSample": True,
    "pageRange": "",
    "tableStrategy": "auto",
    "stitchMultipageTables": True,
    "fillMergedCells": "lattice_only",
    "mergedCellMode": "repeat",
    "headerSeparator": " > ",
    "parseNumbers": False,
    "minConfidence": 0.35,
    "includeMarkdown": True,
    "includeSections": True,
    "markdownTableFormat": "gfm",
    "includeCsv": False,
    "sanitizeCsvFormulas": True,
    "includeRawGrid": False,
    "stripRunningHeadersFooters": True,
    "normalizeUnicode": "ligatures_only",
    "maxPagesPerPdf": 25,
    "maxFileSizeMb": 10,
    "timeoutPerPdfSecs": 30,
}

# Run the Actor and wait for it to finish
run = client.actor("hgreene624/pdf-table-json").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "urls": [],
  "base64Pdfs": [],
  "useBundledSample": true,
  "pageRange": "",
  "tableStrategy": "auto",
  "stitchMultipageTables": true,
  "fillMergedCells": "lattice_only",
  "mergedCellMode": "repeat",
  "headerSeparator": " > ",
  "parseNumbers": false,
  "minConfidence": 0.35,
  "includeMarkdown": true,
  "includeSections": true,
  "markdownTableFormat": "gfm",
  "includeCsv": false,
  "sanitizeCsvFormulas": true,
  "includeRawGrid": false,
  "stripRunningHeadersFooters": true,
  "normalizeUnicode": "ligatures_only",
  "maxPagesPerPdf": 25,
  "maxFileSizeMb": 10,
  "timeoutPerPdfSecs": 30
}' |
apify call hgreene624/pdf-table-json --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,hgreene624/pdf-table-json"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/QM4Q4TeHJfT7Xunb5/builds/Wf18NMcshYATD5HRx/openapi.json
