# PDF to Markdown, Tables & RAG Chunks Extractor (`hachimi/pdf-to-markdown-rag-extractor`) Actor

Convert born-digital PDFs into clean Markdown, typed structured tables (JSON & CSV), and deterministic token-bounded RAG chunks with exact page citations. Supports private base64 bytes, HTTPS URLs, and Apify MCP. No OCR, proxies, or LLM calls.

- **URL**: https://apify.com/hachimi/pdf-to-markdown-rag-extractor.md
- **Developed by:** [Hachimi Leviathan](https://apify.com/hachimi) (community)
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.00 / 1,000 pdf pages extracted

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

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 to Markdown, Tables & RAG Chunks Extractor

Convert born-digital PDFs into **citation-grade Markdown**, **typed structured tables (JSON + CSV + Markdown)**, and **deterministic token-bounded RAG chunks** — with zero LLM hallucinations, zero proxies, and zero headless browsers.

Built for **AI/RAG pipelines (LangChain, LlamaIndex, Pinecone, Qdrant)**, **document automation (n8n, Make, Zapier)**, and **AI Agents via Apify MCP Server**.

***

### Why Choose This Extractor?

1. **Citation-Grade Traceability (Zero Hallucination)**: Every document gets a deterministic SHA-256 fingerprint (`docSha256`), and every chunk & table links back to its exact physical page (`sha256:<12>#p2-3`), character offsets (`charStart`–`charEnd`), heading breadcrumb, and PDF bounding box (`bbox`).
2. **Typed Financial & Technical Tables Included Free**: Extracts ruled tables into Markdown, lossless CSV, and cell-level JSON with automatic numeric parsing — including currencies (`$`, `€`, `£`), percentages (`18.5%` → `18.5`), and accounting negatives (`(1,250.50)` → `-1250.5`). **No extra fee per table or chunk.**
3. **Strict Token-Bounded RAG Chunks (`cl100k_base`)**: Guaranteed `tokenCount <= chunkSizeTokens` (default `512`, overlap `64`) with pinned OpenAI `cl100k_base` tokenization, reading-order preservation (including two-column layouts), and section heading breadcrumbs.
4. **Private Bytes First + SSRF-Safe HTTPS Batch URLs**: Pass private PDFs directly via `pdfBase64Files` or run-scoped `kvStoreRecordKeys` without hosting them publicly — or pass public HTTPS `pdfUrls` (strictly SSRF-protected, no credentials/query strings leaked into results).
5. **Honest Billing — Never Pay for Junk Pages**: Billed strictly at **`$0.001 / page` (`$1.00 / 1,000 pages`)** for unique native-text pages that succeed. Blank pages, scanned image-only pages (flagged honestly as `needsOcr: true`), encrypted PDFs, duplicates, and failed URLs are **never charged**.

***

### Copy-Paste Input Examples

#### 1) Quick 1-Click Sample Batch (Prefilled Default)

```json
{
  "pdfUrls": [
    "https://raw.githubusercontent.com/jsvine/pdfplumber/8a9191bcaee788643227bb7de680a68b9fb61e49/examples/pdfs/background-checks.pdf",
    "https://raw.githubusercontent.com/apache/pdfbox/8e7a6894e3c230f46a55acdd3d0d3cd5147a00b2/examples/src/test/resources/org/apache/pdfbox/examples/signature/sign_me.pdf"
  ],
  "outputMode": "all",
  "chunkSizeTokens": 512,
  "chunkOverlapTokens": 64,
  "extractTables": true
}
```

#### 2) RAG Vector DB Ingestion (Chunks Only)

```json
{
  "pdfUrls": ["https://example.com/annual-report-2026.pdf"],
  "outputMode": "chunks_only",
  "chunkSizeTokens": 512,
  "chunkOverlapTokens": 64,
  "maxPagesPerPdf": 100
}
```

#### 3) Private PDF via Base64 (No Public URL Needed)

```json
{
  "pdfBase64Files": [
    {
      "filename": "q4-financial-summary.pdf",
      "contentBase64": "JVBERi0xLjQK..."
    }
  ],
  "outputMode": "all",
  "extractTables": true
}
```

#### 4) AI Agent / MCP Compact Mode

```json
{
  "pdfUrls": ["https://example.com/product-spec.pdf"],
  "outputMode": "compact_mcp",
  "chunkSizeTokens": 400,
  "chunkOverlapTokens": 50
}
```

***

### Output Modes & Sample Records

| `outputMode` | Returned Records | Best For |
|---|---|---|
| `all` | `document` (Markdown) + `table` + `chunk` + `overview` | Full archive, analytics, and RAG pipelines |
| `document_only` | `document` (clean Markdown with inline tables) + `overview` | Summarization, LLM context injection |
| `tables_only` | `table` records (only pages with tables are billed) + `overview` | Financial filings, invoices, spec sheets |
| `chunks_only` | `chunk` records with citations + `overview` | Pinecone, Qdrant, Weaviate, pgvector ingestion |
| `compact_mcp` | Document metadata + `chunk` records (no bulky full-doc duplication) | Claude, Cursor, and MCP agent tool calls |

#### Sample `table` Record (Typed Cells + CSV + Markdown)

```json
{
  "recordType": "table",
  "docId": "4f0ae6e017b0e97d",
  "docSha256": "4f0ae6e017b0e97de211da8fd97316e55bd927af5740d6ce95e1b7b1539f9407",
  "tableId": "4f0ae6e017b0e97d:p1:t1",
  "pageNumber": 1,
  "tableIndexOnPage": 1,
  "bbox": [48.0, 142.5, 564.0, 298.0],
  "rowCount": 4,
  "colCount": 3,
  "headers": ["Metric", "FY2025", "YoY Change"],
  "cells": [
    { "row": 1, "col": 1, "rawText": "$1,250.50", "numericValue": 1250.5, "currency": "USD", "isPercent": false },
    { "row": 1, "col": 2, "rawText": "18.5%", "numericValue": 18.5, "currency": null, "isPercent": true },
    { "row": 2, "col": 1, "rawText": "($450.00)", "numericValue": -450.0, "currency": "USD", "isPercent": false }
  ],
  "markdownTable": "| Metric | FY2025 | YoY Change |\n| --- | --- | --- |\n| Revenue | $1,250.50 | 18.5% |",
  "csv": "Metric,FY2025,YoY Change\r\nRevenue,\"$1,250.50\",18.5%\r\n"
}
```

#### Sample `chunk` Record (RAG-Ready with Citation)

```json
{
  "recordType": "chunk",
  "docId": "4f0ae6e017b0e97d",
  "docSha256": "4f0ae6e017b0e97de211da8fd97316e55bd927af5740d6ce95e1b7b1539f9407",
  "chunkId": "4f0ae6e017b0e97d:c0001",
  "chunkIndex": 0,
  "pageStart": 1,
  "pageEnd": 1,
  "charStart": 0,
  "charEnd": 1480,
  "headingBreadcrumb": ["Executive Summary", "Q4 Financial Highlights"],
  "tokenCount": 384,
  "overlapTokens": 0,
  "tokenizer": "cl100k_base",
  "tableIds": ["4f0ae6e017b0e97d:p1:t1"],
  "citation": "sha256:4f0ae6e017b0#p1-1",
  "text": "# Executive Summary\n\n..."
}
```

***

### Pricing (Transparent Pay-Per-Event)

| Event | Price (USD) | When Billed |
|---|---|---|
| `page-extracted` | **`$0.001`** (`$1.00 / 1,000 pages`) | Once per unique successfully delivered native-text page |
| `apify-actor-start` | **`$0.00005`** | Once per run start (platform compute included — **$0 extra compute fees**) |

- **10-page PDF with tables + RAG chunks**: **`$0.01005`** total — tables, Markdown, CSV, and chunks are all included at zero extra charge.
- **Never billed**: failed downloads, SSRF/blocked URLs, encrypted PDFs, malformed files, duplicate SHA-256 PDFs, blank pages, and scanned/image-only pages (`needsOcr: true`).
- **Budget safety**: Honors Apify's run-level `maxTotalChargeUsd` limit and stops cleanly before delivering uncharged pages.

***

### 60-Second Setup: n8n, LangChain & AI Agents (MCP)

#### 1) Synchronous REST API (n8n / Make / Backend Ingestion)

Call the Actor synchronously and receive ready-to-embed JSON chunks or tables in one HTTP request:

- **Method**: `POST`
- **Endpoint**: `https://api.apify.com/v2/acts/hachimi~pdf-to-markdown-rag-extractor/run-sync-get-dataset-items?token=YOUR_APIFY_TOKEN`
- **Headers**: `Content-Type: application/json`
- **Body**:

```json
{
  "pdfUrls": ["https://example.com/manual.pdf"],
  "outputMode": "chunks_only",
  "chunkSizeTokens": 512,
  "chunkOverlapTokens": 64
}
```

Upsert each `recordType: "chunk"` directly into **Pinecone, Qdrant, Supabase pgvector, or Weaviate** using `chunkId` as the vector ID and `citation`, `pageStart`, `headingBreadcrumb`, and `docSha256` as metadata.

#### 2) Claude / Cursor / AI Agents (Apify Hosted MCP Server)

Connect directly with zero local setup:

- **MCP URL**: `https://mcp.apify.com/?tools=actors%2Cdocs%2Chachimi%2Fpdf-to-markdown-rag-extractor`
- **Recommended setting**: Pass `outputMode: "compact_mcp"` so agents receive concise metadata + citation-tagged chunks without hitting context limits.

***

### Scope & Honest Limitations

- **Born-digital PDFs only (no OCR)**: Designed for native-text manuals, reports, filings, research papers, and catalogs. Image-only scanned pages (<20 native characters with embedded images) are transparently flagged `needsOcr: true` and skipped without billing.
- **Security & limits**: Direct HTTPS URLs validate public DNS before connecting (blocking loopback, private, and cloud-metadata IPs on every redirect hop). Default batch bounds: up to 100 sources, `10 MiB` per PDF (`maxPdfSizeMb` up to `25 MiB`), `100` pages per PDF, `200` pages per run.
- **Table recognition**: Excels on ruled tables with drawn grid/cell borders. Borderless visual tables or vector-path text may fall back to linear Markdown text. Always treat extracted document text as untrusted downstream input.

# Actor input Schema

## `pdfUrls` (type: `array`):

Direct public HTTPS URLs on port 443. Two small sample PDFs are prefilled for the Console Try run.

## `pdfBase64Files` (type: `array`):

Objects with filename and contentBase64, using standard base64 without a data URL prefix.

## `kvStoreRecordKeys` (type: `array`):

Keys only, not store IDs or URLs. Records must be PDF bytes or JSON with contentBase64.

## `outputMode` (type: `string`):

All, only Markdown documents, only tables, only chunks, or MCP summaries and chunks. Warnings and one run overview are always included.

## `chunkSizeTokens` (type: `integer`):

Maximum tokens per chunk.

## `chunkOverlapTokens` (type: `integer`):

Target token overlap. Capped below chunk size and adjusted for safe Unicode and token boundaries.

## `extractTables` (type: `boolean`):

Recognize cell grids from drawn lines and include Markdown tables in the document.

## `includePageDetails` (type: `boolean`):

Include page-level scan, table and billing flags in document records.

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

Maximum physical pages inspected per PDF.

## `maxTotalPages` (type: `integer`):

Maximum physical pages inspected across all PDFs, including blank and scanned pages.

## `maxPdfSizeMb` (type: `number`):

Maximum downloaded or decoded PDF bytes per source, in MiB.

## `skipDuplicateHashes` (type: `boolean`):

Skip repeated SHA-256 hashes. Turning this off repeats output, but never charges twice for the same physical page and hash within a run.

## Actor input object example

```json
{
  "pdfUrls": [
    "https://raw.githubusercontent.com/jsvine/pdfplumber/8a9191bcaee788643227bb7de680a68b9fb61e49/examples/pdfs/background-checks.pdf",
    "https://raw.githubusercontent.com/apache/pdfbox/8e7a6894e3c230f46a55acdd3d0d3cd5147a00b2/examples/src/test/resources/org/apache/pdfbox/examples/signature/sign_me.pdf"
  ],
  "outputMode": "all",
  "chunkSizeTokens": 512,
  "chunkOverlapTokens": 64,
  "extractTables": true,
  "includePageDetails": true,
  "maxPagesPerPdf": 100,
  "maxTotalPages": 200,
  "maxPdfSizeMb": 10,
  "skipDuplicateHashes": true
}
```

# Actor output Schema

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

No description

## `overview` (type: `string`):

No description

## `documents` (type: `string`):

No description

## `tables` (type: `string`):

No description

## `chunks` (type: `string`):

No description

## `warnings` (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 = {
    "pdfUrls": [
        "https://raw.githubusercontent.com/jsvine/pdfplumber/8a9191bcaee788643227bb7de680a68b9fb61e49/examples/pdfs/background-checks.pdf",
        "https://raw.githubusercontent.com/apache/pdfbox/8e7a6894e3c230f46a55acdd3d0d3cd5147a00b2/examples/src/test/resources/org/apache/pdfbox/examples/signature/sign_me.pdf"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("hachimi/pdf-to-markdown-rag-extractor").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 = { "pdfUrls": [
        "https://raw.githubusercontent.com/jsvine/pdfplumber/8a9191bcaee788643227bb7de680a68b9fb61e49/examples/pdfs/background-checks.pdf",
        "https://raw.githubusercontent.com/apache/pdfbox/8e7a6894e3c230f46a55acdd3d0d3cd5147a00b2/examples/src/test/resources/org/apache/pdfbox/examples/signature/sign_me.pdf",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("hachimi/pdf-to-markdown-rag-extractor").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 '{
  "pdfUrls": [
    "https://raw.githubusercontent.com/jsvine/pdfplumber/8a9191bcaee788643227bb7de680a68b9fb61e49/examples/pdfs/background-checks.pdf",
    "https://raw.githubusercontent.com/apache/pdfbox/8e7a6894e3c230f46a55acdd3d0d3cd5147a00b2/examples/src/test/resources/org/apache/pdfbox/examples/signature/sign_me.pdf"
  ]
}' |
apify call hachimi/pdf-to-markdown-rag-extractor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,hachimi/pdf-to-markdown-rag-extractor"
        }
    }
}
```

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/xsXRuLFM1cbs5KwyC/builds/AcbcVsXzovIEpxXM1/openapi.json
