# PDF to Markdown & OCR for RAG (Arabic, French, English) (`kasbahdata/pdf-to-rag-markdown`) Actor

Convert PDFs, scans and images into clean Markdown and token-sized chunks for RAG and AI agents. Keeps headings and tables, reads Arabic right-to-left correctly, and OCRs scanned pages in Arabic, French and English.

- **URL**: https://apify.com/kasbahdata/pdf-to-rag-markdown.md
- **Developed by:** [Kasbah Data](https://apify.com/kasbahdata) (community)
- **Categories:** AI, Developer tools, Automation
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $3.00 / 1,000 text pages

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/running/actors-in-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 & OCR for RAG (Arabic, French, English)

**PDF to Markdown, PDF to text and OCR in one Actor.** Turn PDFs, scans and images into clean Markdown and token-sized chunks you can drop straight into a RAG pipeline, a vector database or an AI agent. Built for documents that generic converters get wrong: **Arabic text comes out in the right reading order**, French and English stay intact, and scanned pages are read with OCR in all three languages.

### What it does

- **Keeps document structure.** Headings become `#`, `##`, `###`; bullet and numbered lists become Markdown lists; ruled tables become Markdown tables and are also returned as rows.
- **Reads Arabic correctly.** Right-to-left lines are put back in logical order, numbers and Latin words inside Arabic sentences are not reversed, presentation-form glyphs are folded to normal letters, and Arabic tables keep their column order.
- **OCRs scanned pages automatically.** In `auto` mode each page's text layer is checked; only pages that are scans (or have broken text) go through OCR, in Arabic, French and English.
- **Chunks for retrieval.** Heading-aware chunks with a target token size and overlap. Chunks never end on a heading and never split a table row; big tables are split by rows with the header repeated. Each chunk carries its section path and page range, so answers can cite their source.
- **Cleans the noise.** Running headers, footers and page numbers are removed; `<!-- page N -->` markers are kept for citations.

### Input

```json
{
  "startUrls": [
    { "url": "https://example.com/annual-report-2024.pdf" },
    { "url": "https://example.com/scanned-contract.pdf" }
  ],
  "ocrMode": "auto",
  "ocrLanguages": "ara+fra+eng",
  "outputMode": "document",
  "chunkSizeTokens": 512,
  "chunkOverlapTokens": 64
}
```

Link directly to the file, not to a viewer page. PDFs and images (PNG, JPEG, TIFF, WebP, multi-page TIFF) are supported.

### Output

With `outputMode: "document"`, one item per document:

```json
{
  "url": "https://example.com/annual-report-2024.pdf",
  "fileName": "annual-report-2024.pdf",
  "title": "Rapport annuel 2024",
  "language": "fr",
  "pageCount": 2,
  "textPages": 2,
  "ocrPages": 0,
  "markdown": "<!-- page 1 -->\n\n# Rapport annuel 2024\n\nCe rapport présente…\n\n## 1. Résultats financiers\n\n| Indicateur | 2023 | 2024 | Variation |\n| --- | --- | --- | --- |\n| Chiffre d'affaires (M€) | 3,65 | 4,20 | +15 % |",
  "chunks": [
    {
      "index": 1,
      "text": "## 2. Priorités pour 2025\n\n- Lancer l'offre de traitement documentaire en arabe et en français.\n- …",
      "tokens": 155,
      "pageStart": 1,
      "pageEnd": 2,
      "headingPath": ["Rapport annuel 2024", "2. Priorités pour 2025"]
    }
  ],
  "tables": [{ "page": 1, "rows": [["Indicateur", "2023", "2024", "Variation"], ["Chiffre d'affaires (M€)", "3,65", "4,20", "+15 %"]] }],
  "metadata": { "Title": "Rapport annuel 2024", "Producer": "LibreOffice 24.2" },
  "truncated": false,
  "warnings": []
}
```

With `outputMode: "chunks"`, one item per chunk (`text`, `tokens`, `pageStart`, `pageEnd`, `headingPath`, plus the document's `url`, `fileName`, `title` and `language`), ready to embed and load into any vector database.

Documents that cannot be read produce an item with `url` and `error` and are not charged. A run summary with per-document page counts and warnings is saved as the `OUTPUT` record in the run's key-value store.

### Use it from your code

Call it like a **PDF-to-Markdown API** from your own pipeline (LangChain, LlamaIndex, n8n, a cron job...):

**Python** (`pip install apify-client`)

```python
from apify_client import ApifyClient

client = ApifyClient("<YOUR_APIFY_TOKEN>")
run = client.actor("kasbahdata/pdf-to-rag-markdown").call(run_input={
    "startUrls": [
        {
            "url": "https://arxiv.org/pdf/1706.03762"
        }
    ],
    "outputMode": "chunks"
})
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)
```

**JavaScript** (`npm install apify-client`)

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

const client = new ApifyClient({ token: '<YOUR_APIFY_TOKEN>' });
const run = await client.actor('kasbahdata/pdf-to-rag-markdown').call({
    "startUrls": [
        {
            "url": "https://arxiv.org/pdf/1706.03762"
        }
    ],
    "outputMode": "chunks"
});
const { items } = await client.dataset(run.defaultDatasetId).listItems();
console.log(items);
```

**HTTP** (one request, waits for the results)

```bash
curl -X POST "https://api.apify.com/v2/acts/kasbahdata~pdf-to-rag-markdown/run-sync-get-dataset-items?token=<YOUR_APIFY_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{"startUrls": [{"url": "https://arxiv.org/pdf/1706.03762"}], "outputMode": "chunks"}'
```

Your token is under **Settings → API & Integrations** in Apify Console. The Actor also works in Make, Zapier, n8n
and from AI agents through the Apify MCP server.

### Pricing

You pay per page processed, plus a tiny start fee per run:

| Event | Price |
| --- | --- |
| Text page (read from the PDF text layer) | $3 per 1,000 pages |
| OCR page (scanned page or image) | $6 per 1,000 pages |
| Actor start (once per run) | $0.0001 at the default 2 GB of memory ($0.00005 per GB) |

There is no charge per result and no platform usage fee. Empty pages, pages that fail, and documents that cannot be downloaded are free. The run stops cleanly at your maximum charge per run, and pages beyond **Max pages per document** are never processed.

### Use it from AI agents

The Actor works as a tool through the [Apify MCP server](https://mcp.apify.com): add it to your MCP client configuration and an agent can convert any document URL to Markdown on demand.

### Good to know

- **Token counts are estimates** (about 4 characters per token for Latin script, 2 for Arabic). They are close to common OpenAI-style tokenizers but not exact for any one model.
- **OCR pages** keep headings and paragraphs, but table structure is not reconstructed from images yet.
- **Multi-column layouts** (such as academic papers) are read line by line across the full page width in this version.
- **Password-protected PDFs** cannot be opened.
- OCR quality depends on the scan. Pages below 60% OCR confidence are flagged in `warnings`; try `ocrDpi: 400` for small print.

### Feedback

Found a document it gets wrong, or need a field it doesn't return? Open an issue on the **Issues** tab and I'll look at it. If the Actor saved you time, a short review on the Actor page helps other people find it.

# Actor input Schema

## `startUrls` (type: `array`):

Direct links to PDF files or images (PNG, JPEG, TIFF, WebP). Link to the file itself, not to a viewer page.

## `ocrMode` (type: `string`):

Auto reads the text layer and runs OCR only on scanned pages. Always ignores the text layer. Never skips OCR entirely. Text pages and OCR pages are billed differently.

## `ocrLanguages` (type: `string`):

Languages to recognize on scanned pages. Fewer languages is faster and slightly more accurate.

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

One dataset item per document (full Markdown plus its chunks), or one item per chunk, ready for a vector database.

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

Target chunk size in estimated tokens. Chunks never split a table row and never end on a heading.

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

Text repeated from the end of one chunk at the start of the next, for retrieval context. At most half the chunk size.

## `chunkContextHeader` (type: `boolean`):

Start each chunk with its heading path (e.g. "Annual report > Results"), which usually improves retrieval.

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

Convert ruled tables into Markdown tables and add them to the tables field.

## `removeHeadersFooters` (type: `boolean`):

Drop page numbers and lines that repeat at the top or bottom of most pages, so they do not pollute chunks.

## `includePageMarkers` (type: `boolean`):

Insert  comments so answers can cite pages.

## `ocrDpi` (type: `integer`):

Higher helps small print but is slower.

## `maxPagesPerDocument` (type: `integer`):

Pages after this limit are not processed or billed.

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

Files larger than this are skipped with an error and not charged.

## `proxyConfiguration` (type: `object`):

Only needed when a host blocks direct downloads.

## Actor input object example

```json
{
  "startUrls": [
    {
      "url": "https://arxiv.org/pdf/1706.03762"
    }
  ],
  "ocrMode": "auto",
  "ocrLanguages": "ara+fra+eng",
  "outputMode": "document",
  "chunkSizeTokens": 512,
  "chunkOverlapTokens": 64,
  "chunkContextHeader": true,
  "extractTables": true,
  "removeHeadersFooters": true,
  "includePageMarkers": true,
  "ocrDpi": 300,
  "maxPagesPerDocument": 500,
  "maxFileSizeMb": 100,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

# Actor output Schema

## `results` (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 = {
    "startUrls": [
        {
            "url": "https://arxiv.org/pdf/1706.03762"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("kasbahdata/pdf-to-rag-markdown").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 = { "startUrls": [{ "url": "https://arxiv.org/pdf/1706.03762" }] }

# Run the Actor and wait for it to finish
run = client.actor("kasbahdata/pdf-to-rag-markdown").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 '{
  "startUrls": [
    {
      "url": "https://arxiv.org/pdf/1706.03762"
    }
  ]
}' |
apify call kasbahdata/pdf-to-rag-markdown --silent --output-dataset

```

## MCP server setup

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

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/6rdgn564OGHZfyjaZ/builds/a3Fl1HlMVBes2ZnAx/openapi.json
