# PDF to Markdown for AI agents (`lundrik/pdf-to-markdown`) Actor

Convert PDF URLs to clean Markdown for LLMs, RAG and AI agents: headings, per-page text and metadata. Flat price per PDF; locked, scanned or failed PDFs are free.

- **URL**: https://apify.com/lundrik/pdf-to-markdown.md
- **Developed by:** [Lundrik](https://apify.com/lundrik) (community)
- **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 pdf documents

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 for AI agents — with OCR for scanned PDFs

Turn PDF links into **clean Markdown** that LLMs, RAG pipelines and AI agents can read: headings, paragraphs, bullet lists, page markers, per-page text and document metadata. **Scanned pages are read with built-in OCR** (8 languages), and **you only pay for PDFs that were converted** — locked, broken, empty or unreachable files are free.

### Why this Actor

| | This Actor | Typical PDF text extractors |
|---|---|---|
| Scanned pages | ✅ OCR **only on pages that need it** (`ocr: auto`) – normal PDFs stay fast | Often all-or-nothing, or no OCR |
| Mixed PDFs (text + scanned pages) | ✅ text layer where it exists, OCR where it does not | One method for the whole file |
| Broken / garbled text layer | ✅ `ocr: force` re-reads the pages with OCR | Garbage text returned as-is |
| Lithuanian, Polish, German, French, Spanish, Italian, Portuguese, English | ✅ choose 1–3 OCR languages | Usually English only |
| Failed, locked, empty files | ✅ **free**, with a clear error code | Often charged or silently empty |
| Start fee | ✅ none (only Apify's tiny standard fee) | Often $0.005 per run |
| Markdown structure | ✅ headings, lists, page markers, per-page text | Plain text |
| Password-protected PDFs | ✅ `pdfPassword` (your own documents) | Often unsupported |

### What you get

- **Markdown with structure** – headings (`#`, `##`, `###`) detected from font sizes, paragraphs re-joined across line breaks (including hyphenated words), bullet lists as `- item`.
- **OCR for scanned pages** – open-source Tesseract runs inside the Actor (no third-party API, your files are not sent anywhere). Each OCR page is marked `ocr: true` in `pageTexts`; `ocrPages` and `ocrConfidence` (0–100) are in every row.
- **Page markers** – `<!-- page 3 -->` before every page, so you can cite page numbers.
- **Per-page Markdown** (`pageTexts`) – one entry per page, ready for chunking.
- **Metadata** – title, author, subject, keywords, creator, producer, creation and modification date, language, PDF version, page count. If the PDF has no title, the main heading of the first pages is used.
- **Links** found in the PDF (URL annotations).
- **A `.md` file** for every document in the key-value store (`markdownUrl`) – also for very large documents that do not fit into a dataset row.
- **Clear errors** instead of empty output: wrong password, empty scan, not a PDF, too large, unreachable.

### OCR in short

| `ocr` | What happens | Use it for |
|---|---|---|
| `auto` (default) | A page is OCR'd only if it contains an image **and** has almost no text layer. Blank pages are skipped. | Everyday mix of digital and scanned PDFs |
| `force` | The first `maxOcrPages` pages are OCR'd and the OCR text replaces their text layer (if OCR found text); later pages keep their text layer. | Old scans with a garbled "invisible" text layer |
| `off` | No OCR. A scanned PDF returns `PDF_NO_TEXT_LAYER` (free). | Maximum speed, digital PDFs only |

- `ocrLanguages`: `en`, `de`, `fr`, `es`, `it`, `pt`, `lt`, `pl` (1–3 at once; Tesseract codes like `eng`, `lit` also work). Choose the document language – it matters for letters like ą, č, ė, ł, ß, é.
- `maxOcrPages` (default **3**, max **5**): OCR takes a few seconds per page, so the number of OCR pages per PDF is limited. Scanned pages above the limit stay empty, are listed in `ocrSkippedPages`, explained in `note` and **not charged** (they are not counted in `pagesCharged`).
- OCR pages give paragraphs and lists; headings are guessed from larger text lines. Tables come out as text lines.
- Handwriting is not supported.

### Input

| Field | Default | Description |
|---|---|---|
| `urls` | – (required) | Direct links to PDF files. Redirects are followed. Duplicates are removed. |
| `ocr` | `auto` | `auto`, `force` or `off` (see above). |
| `ocrLanguages` | `["en"]` | OCR languages, 1–3 of `en de fr es it pt lt pl`. |
| `maxOcrPages` | 3 | Max pages read with OCR per PDF (0–5). Unread scanned pages are not charged. |
| `pdfPassword` | – | Password for protected PDFs you are allowed to open. Stored as a secret input, never written to results. |
| `maxFileSizeMb` | 50 | Files above this size are not downloaded (max 100). |
| `maxPages` | 1000 | Only the first N pages are converted **and charged**. |
| `includePageTexts` | `true` | Add `pageTexts` (Markdown per page). |
| `downloadTimeoutSecs` | 60 | Time limit for downloading one file. |
| `maxConcurrency` | 0 (auto = 3) | PDFs processed in parallel. |

```json
{
  "urls": ["https://bitcoin.org/bitcoin.pdf", "https://example.com/scanned-contract.pdf"],
  "ocr": "auto",
  "ocrLanguages": ["en", "lt"]
}
```

### Output

One dataset row per PDF (example, shortened):

```json
{
  "url": "https://bitcoin.org/bitcoin.pdf",
  "status": "ok",
  "title": "Bitcoin: A Peer-to-Peer Electronic Cash System",
  "pages": 9,
  "pagesConverted": 9,
  "markdown": "<!-- page 1 -->\n\n# Bitcoin: A Peer-to-Peer Electronic Cash System\n\nSatoshi Nakamoto ...",
  "pageTexts": [{ "page": 1, "markdown": "# Bitcoin: A Peer-to-Peer Electronic Cash System ..." }],
  "metadata": { "title": "Bitcoin: A Peer-to-Peer Electronic Cash System", "creator": "Writer", "producer": "OpenOffice.org 2.4", "creationDate": "2009-03-24T11:33:15Z", "language": "en-GB", "pdfVersion": "1.4" },
  "ocrPages": [],
  "ocrSkippedPages": [],
  "ocrConfidence": null,
  "markdownChars": 21517,
  "markdownUrl": "https://api.apify.com/v2/key-value-stores/.../records/bitcoin-org-bitcoin-pdf-1a2b3c4d.md?signature=...",
  "charged": "pdf-document",
  "errorCode": null
}
```

A scanned PDF looks the same, with `"ocrPages": [1, 2, 3]`, `"ocrConfidence": 93`, `"ocrLanguages": ["eng"]` and `"ocr": true` on those pages in `pageTexts`.

- `status`: `ok` (converted – charged), `error` (see `errorCode` – free), `skipped` (your maximum cost per run was reached – free).
- Documents with more than 30 charged pages also have `chargedExtra: { "event": "pdf-extra-page", "count": N }`. `pagesCharged` = converted pages minus scanned pages that were not read with OCR.
- If the Markdown is too large for a dataset row (several MB), `markdown` and `pageTexts` are `null` and the full text is in `markdownUrl`.

#### Error codes (all free of charge)

| Code | Meaning |
|---|---|
| `PDF_ENCRYPTED` | The PDF needs a password. Add it in `pdfPassword` if you are allowed to open the file. We do not crack passwords. |
| `PDF_PASSWORD_INCORRECT` | The password in `pdfPassword` is wrong. |
| `PDF_NO_TEXT_LAYER` | No readable text: blank pages, an unreadable scan, OCR turned off, or `maxOcrPages` = 0. |
| `PDF_INVALID` | The file is damaged or not a readable PDF. |
| `NOT_PDF` | The URL returned something else (a web page, a ZIP…). Use a direct link to the `.pdf`. |
| `FILE_TOO_LARGE` | The file is larger than `maxFileSizeMb`. |
| `HTTP_ERROR` | The server returned 404, 500… |
| `BLOCKED_BY_BOT_PROTECTION` | The server refused automated access (HTTP 401/403/429). We do not bypass protection. |
| `TIMEOUT`, `CONNECTION_FAILED`, `SSL_ERROR`, `DNS_NOT_FOUND`, `INVALID_URL` | The file could not be downloaded. |

### Pricing

| Event | Price | When |
|---|---|---|
| `pdf-document` | **$0.003** per PDF | Each PDF converted successfully – includes the first 30 pages, **also when some pages were read with OCR**. |
| `pdf-extra-page` | **$0.0002** per page | Each converted page above 30 in the same PDF (scanned pages not read with OCR do not count). |

Examples: a 10-page PDF = $0.003; a 3-page scanned letter read with OCR = $0.003; a 100-page PDF = $0.003 + 70 × $0.0002 = **$0.017**; 1,000 short PDFs = **$3.00**.

- Failed, locked, empty and too-large PDFs are **free**.
- Use `maxPages` to cap the price of very long documents.
- Apart from the tiny Apify start fee (Apify standard, $0.00005 per GB of memory per run), you pay only for converted PDFs.
- Set *Maximum cost per run* in the run options: a PDF whose pages would not fit into the remaining budget is not converted (marked `skipped`, free).

### Use with AI agents (MCP)

The Actor is a ready-made tool for AI agents through the [Apify MCP server](https://mcp.apify.com): the agent passes PDF links and reads Markdown back.

```json
{
  "mcpServers": {
    "apify": {
      "url": "https://mcp.apify.com/?tools=lundrik/pdf-to-markdown",
      "headers": { "Authorization": "Bearer <YOUR_APIFY_TOKEN>" }
    }
  }
}
```

Example prompt: *"Read https://example.com/annual-report.pdf with the PDF to Markdown tool and list the three biggest risks with page numbers."* The agent gets `markdown` with `<!-- page N -->` markers (or `pageTexts` for citations).

From code (JavaScript):

```js
import { ApifyClient } from 'apify-client';
const client = new ApifyClient({ token: process.env.APIFY_TOKEN });
const run = await client.actor('lundrik/pdf-to-markdown').call({ urls: ['https://bitcoin.org/bitcoin.pdf'], ocrLanguages: ['en'] });
const { items } = await client.dataset(run.defaultDatasetId).listItems();
console.log(items[0].markdown);
```

### FAQ

**My scanned PDF came back with only some pages.** OCR is limited by `maxOcrPages` (max 5 per PDF). The row lists the pages that were not read in `ocrSkippedPages`; they are not charged. Split long scans or convert the important pages first.

**The OCR text has mistakes.** Check that `ocrLanguages` matches the document and look at `ocrConfidence` (below ~70 = poor scan). Low-resolution, skewed or handwritten pages give weaker results.

**Can I OCR a PDF that already has text?** Yes – `ocr: "force"` re-reads the first `maxOcrPages` pages. Useful when copy-paste from the PDF gives garbage.

**Is my document sent to a third-party OCR service?** No. OCR runs inside the Actor with open-source Tesseract.

**Does it extract tables?** Tables come out as text lines, not Markdown tables.

**Can I use files from Google Drive or Dropbox?** Use a direct download link that returns the PDF itself (not a preview page).

### Notes

- Only files you link to are downloaded; nothing else is crawled.
- Private and local network addresses are blocked.
- You are responsible for having the right to process the documents you submit.
- OCR: [Tesseract](https://github.com/tesseract-ocr/tesseract) via tesseract.js (Apache-2.0), `tessdata_fast` models (Apache-2.0).

# Actor input Schema

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

Direct links to PDF files (http/https), one per line. Redirects are followed, duplicates are removed. Scanned PDFs are read with OCR.

## `ocr` (type: `string`):

auto (recommended): a page is read with OCR only if it has an image and almost no text layer, so normal PDFs are not slowed down. force: OCR the first maxOcrPages pages and replace a broken or garbled text layer (later pages keep their text layer). off: no OCR – scanned PDFs return PDF_NO_TEXT_LAYER (free).

## `ocrLanguages` (type: `array`):

Languages of the scanned documents (1–3). Picking the right language matters for accents and letters like ą, č, ß, é, ł. Tesseract codes (eng, deu, lit…) are accepted too.

## `maxOcrPages` (type: `integer`):

Upper limit of pages read with OCR in one PDF (OCR takes a few seconds per page). Scanned pages above the limit stay empty, are listed in ocrSkippedPages and are not charged. 0 = no OCR.

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

Larger files are not downloaded (error FILE_TOO_LARGE, free of charge).

## `maxPages` (type: `integer`):

Only the first N pages are converted and charged. Use it to cap the price of very long documents.

## `includePageTexts` (type: `boolean`):

Adds `pageTexts` (Markdown of each page separately) to every row – handy for citations and chunking.

## `downloadTimeoutSecs` (type: `integer`):

Maximum time to download one file.

## `maxConcurrency` (type: `integer`):

How many PDFs are processed in parallel. 0 = automatic (3).

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

Password for protected PDFs you have the right to open. Used for every PDF in the run; never stored in results. We do not crack passwords.

## Actor input object example

```json
{
  "urls": [
    "https://bitcoin.org/bitcoin.pdf"
  ],
  "ocr": "auto",
  "ocrLanguages": [
    "en"
  ],
  "maxOcrPages": 3,
  "maxFileSizeMb": 50,
  "maxPages": 1000,
  "includePageTexts": true,
  "downloadTimeoutSecs": 60,
  "maxConcurrency": 0
}
```

# Actor output Schema

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

Dataset rows: url, status (ok | error | skipped), title, author, pages, markdownUrl, errorCode.

## `files` (type: `string`):

Default key-value store with one .md file per converted PDF (and the RUN_SUMMARY record).

# 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": [
        "https://bitcoin.org/bitcoin.pdf"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("lundrik/pdf-to-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 = { "urls": ["https://bitcoin.org/bitcoin.pdf"] }

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

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,lundrik/pdf-to-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/G5RMD8uVsnYjygiI1/builds/tNvoYMgyoWhSorcr0/openapi.json
