# PDF to Markdown - PDF Text Extractor with OCR, Tables & RAG (`sonic_scraper/pdf-to-markdown`) Actor

Convert PDF URLs to clean Markdown or text for LLMs and RAG: headings, tables, multi-column layouts and scanned pages (OCR in 16 languages). One row per document, page or token-sized chunk with page numbers. Also finds every PDF linked from a web page.

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

## Pricing

from $1.40 / 1,000 pdf converteds

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

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 - PDF Text Extractor with OCR, Tables & RAG

**Convert any PDF URL into clean Markdown or plain text for LLMs, RAG pipelines and AI agents. Headings, lists and ruled tables are kept, two- and three-column layouts are read in the right order, running headers and page numbers are removed, and scanned pages are read with OCR in 16 languages. Get one row per document, per page, or per token-sized chunk with its section path and page numbers. It can also find and convert every PDF linked from a web page.**

Paste PDF links (or arXiv, journal and landing pages, Google Drive and Dropbox share links) and run. No API key, no browser, no setup.

![PDF to Markdown output: a two-column research paper and an IRS table converted to Markdown with headings and a Markdown table](https://api.apify.com/v2/key-value-stores/lwQu1lCMCLQIIhSMQ/records/pdf-to-markdown-output.png)

*Real output from runs of PDF to Markdown: a two-column arXiv paper and a ruled table from the IRS Form 1040 instructions.*

### What makes it different

- **Reading order that survives columns.** Two- and three-column pages (papers, newsletters, government booklets) are read column by column, while titles and abstracts that span the page stay in place.
- **Real structure, not a text dump.** Headings are detected from font size, weight and section numbering (`## 1 Introduction`, `### 2.1 ...`), bullets become Markdown lists, ruled tables become Markdown tables, and words hyphenated across lines are joined.
- **Noise removed.** Repeated running headers and footers, page numbers, printer's marks outside the page and sideways margin stamps (like arXiv's) are dropped.
- **Scanned pages too.** Pages with no text layer are read with Tesseract OCR, automatically, in up to 4 of 16 languages. Pages that have text are never billed as OCR.
- **Ready for RAG.** Chunk mode splits each document into pieces of about N tokens that start at section boundaries and carry their `headingPath` (for example `["Attention Is All You Need", "3 Model Architecture"]`) and `pageStart` / `pageEnd`, so answers can cite pages.
- **Built for agents.** Runs on an empty input (it converts a sample, free), returns a status row for every failed URL instead of an empty dataset, and keeps one flat JSON shape.

### Quick start

Convert two PDFs into one Markdown row each:

```json
{ "pdfUrls": ["https://www.irs.gov/pub/irs-pdf/fw9.pdf", "https://arxiv.org/abs/1706.03762"] }
```

Chunks of about 500 tokens for a vector database:

```json
{
  "pdfUrls": ["https://arxiv.org/abs/1706.03762"],
  "splitBy": "chunk",
  "chunkSize": 500,
  "chunkOverlap": 50
}
```

Every PDF linked from a reports page, first 20 pages each:

```json
{
  "pageUrls": ["https://www.irs.gov/forms-pubs/about-form-w-9"],
  "maxPdfsPerPage": 20,
  "pageRange": "1-20"
}
```

A scanned French and English document, one row per page:

```json
{
  "pdfUrls": ["https://example.com/scanned-contract.pdf"],
  "splitBy": "page",
  "ocrLanguages": ["fra", "eng"]
}
```

### What you get

| Field | Example |
|---|---|
| `status`, `error` | `ok`, or `error` with a reason (download failed, not a PDF, password-protected...) |
| `url`, `finalUrl`, `foundOn` | The URL you gave, where it redirected, and the web page it was found on |
| `title`, `author`, `subject`, `keywords`, `creator`, `producer` | From the PDF's metadata; the title falls back to the first heading |
| `createdAt`, `modifiedAt` | `2019-05-28T00:07:51` |
| `fileName`, `fileSizeBytes`, `pageCount`, `pagesConverted` | `1810.04805v2.pdf`, `775166`, `16`, `16` |
| `ocrPages`, `tableCount`, `wordCount` | `0`, `3`, `10700` |
| `markdown` and/or `text` | The converted content |
| `pageNumber`, `ocr`, `pageTables` | Page mode |
| `chunkIndex`, `chunkCount`, `headingPath`, `pageStart`, `pageEnd`, `tokenEstimate` | Chunk mode |
| `markdownFileUrl` | Download link of a `.md` file (with `saveMarkdownFiles`, and always for documents over 1 million characters) |
| `warnings` | For example "only the first 500 of 812 pages were converted (maxPagesPerPdf)" |

Shortened chunk row from a real run:

```json
{
  "status": "ok",
  "url": "https://arxiv.org/abs/1706.03762",
  "fileName": "1706.03762v7.pdf",
  "title": "Attention Is All You Need",
  "pageCount": 15,
  "chunkIndex": 6,
  "chunkCount": 35,
  "headingPath": ["Attention Is All You Need", "3 Model Architecture"],
  "pageStart": 2,
  "pageEnd": 3,
  "tokenEstimate": 194,
  "markdown": "## 3 Model Architecture\n\nMost competitive neural sequence transduction models have an encoder-decoder structure [5, 2, 35]. Here, the encoder maps an input sequence of symbol representations (x 1,..., x n) to a sequence of continuous representations z = (z 1,..., z n). ..."
}
```

The **Documents** view lists status, title, pages, OCR pages, tables and words; the **Markdown** view shows the content. Export as JSON, CSV or Excel, or send rows to a vector database, Google Sheets or a webhook with Apify integrations, Make, Zapier or n8n.

### Options

| Field | What it does |
|---|---|
| `pdfUrls` | PDF links. Article and landing pages are followed to their PDF (citation metadata or the first PDF link); arXiv `/abs/` links, Google Drive and Dropbox share links are converted to downloads. |
| `pageUrls`, `maxPdfsPerPage` | Web pages whose PDF links should all be converted. |
| `splitBy` | `document` (default), `page` or `chunk`. |
| `chunkSize`, `chunkOverlap` | Chunk size and overlap in tokens (about 4 characters per token). |
| `outputFormat` | `markdown` (default), `text` (tables as tab-separated rows) or `both`. |
| `pageRange`, `maxPagesPerPdf` | Pages to convert, for example `1-5, 8, 20-`. |
| `ocrMode`, `ocrLanguages` | `auto` (pages without a text layer), `off` or `force`; up to 4 languages. |
| `includeTables`, `includePageMarkers` | Markdown tables on/off; `<!-- page N -->` markers in document Markdown. |
| `saveMarkdownFiles` | Also save each document as a `.md` file and return its link. |
| `maxPdfs`, `maxFileSizeMb`, `pdfPassword`, `maxConcurrency`, `proxyConfiguration` | Limits, protected PDFs, parallel files and an optional proxy. |

### How it works

The Actor downloads each PDF over plain HTTP, reads every page's words with their position, font size and weight (pdfplumber and pdfium), and rebuilds the reading order: it finds column gutters, groups words into lines and paragraphs, detects headings, lists and ruled tables, and removes repeated headers, footers and page numbers. Pages without a text layer are rendered at 300 DPI and read with Tesseract OCR. Everything runs inside the Actor; your documents are not sent to any third-party API or language model.

A text page takes about half a second at the default 4 GB of memory, and a scanned page a few seconds.

### Use with AI agents / MCP

Connect the Apify MCP server at `https://mcp.apify.com?tools=sonic_scraper/pdf-to-markdown` in Claude Desktop, Cursor, VS Code or any MCP client. Example prompt: *"Read this annual report PDF and list the revenue figures by segment: https://example.com/annual-report.pdf"*. With `splitBy: "chunk"` an agent gets section-tagged pieces it can quote with page numbers.

### Pricing

Pay per use, on the free plan:

| Event | Price |
|---|---|
| PDF converted | $2 per 1,000 PDFs ($0.002 each) |
| Text page converted | $0.30 per 1,000 pages |
| Scanned page read with OCR | $4 per 1,000 pages |

Paid Apify plans get lower rates (see the Pricing tab). Failed downloads, files that are not PDFs, password errors and the free sample run are **not charged**, and a page is billed either as a text page or as an OCR page, never both.

Examples: a 20-page report costs $0.008; 1,000 reports of 20 pages cost $8; a 50-page scanned contract costs $0.20. The Actor stops before your run's maximum charge.

### Limits

- **Tables need ruling lines.** Tables drawn with lines (most forms, statements and government documents) become Markdown tables. Tables laid out only with spacing, like many academic tables, come out as text lines in reading order.
- **Figures are not described.** Images, charts and diagrams are skipped; their text labels may appear as short lines.
- **Math** is kept as plain text with subscripts inline (`x 1` for x₁), not LaTeX.
- **Complex forms and posters** with text boxes scattered across the page convert in a readable but imperfect order.
- **OCR quality follows scan quality.** Clear 200-300 DPI scans read well; photos, handwriting and very small print less so.
- **Some sites block automated downloads.** If a host refuses, try `proxyConfiguration`; files behind a login cannot be fetched.

### FAQ

#### How do I convert a PDF to Markdown?

Put the PDF's URL in `pdfUrls` and start the Actor. Each PDF comes back as one row with its Markdown in the `markdown` field, plus title, author, page count and table count.

#### Can it read scanned PDFs?

Yes. With `ocrMode: "auto"` (the default), pages that have no text layer are read with OCR. Set `ocrLanguages` to the document's languages, for example `["deu", "eng"]`.

#### How do I prepare PDFs for RAG or a vector database?

Use `splitBy: "chunk"` with a `chunkSize` that suits your embedding model (300-800 tokens is common). Each chunk has a `headingPath` and page range you can store as metadata.

#### Can I convert all PDFs on a website page?

Yes. Put the page in `pageUrls`; every PDF it links to (up to `maxPdfsPerPage`) is converted, and each row shows the page it was found on in `foundOn`.

#### Can I upload a PDF from my computer?

Upload it somewhere that gives a direct link (an Apify key-value store, Google Drive or Dropbox share link, S3) and use that link in `pdfUrls`.

#### Does it extract images?

No. It extracts text, structure and tables. Images and charts are skipped.

### Related actors

- [AI Web Crawler for RAG](https://apify.com/sonic_scraper/ai-rag-web-crawler): crawl websites into Markdown for LLMs.
- [Website Screenshot API](https://apify.com/sonic_scraper/website-screenshot-api): full-page screenshots and PDF captures of web pages.
- [SEC Form D Filings](https://apify.com/sonic_scraper/sec-form-d-filings): recently funded companies from SEC filings.

Questions or a PDF that converts badly? Open an issue on the Issues tab with the PDF URL and your run ID.

# Actor input Schema

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

Direct links to PDF files. Article or landing pages (arXiv, journals) are followed to their PDF, and Google Drive and Dropbox share links are converted to downloads. Leave empty to convert a sample PDF for free.

## `pageUrls` (type: `array`):

Web pages whose PDF links should all be converted, for example an investor-relations, reports or downloads page.

## `maxPdfsPerPage` (type: `integer`):

How many PDF links to take from each web page in 'Web pages to find PDFs on'.

## `splitBy` (type: `string`):

Document: the whole PDF in one row. Page: one row per page. Chunk: token-sized pieces for RAG and vector databases, each with its heading path and page range.

## `chunkSize` (type: `integer`):

Target size of each chunk, in tokens (about 4 characters each). Used when 'One row per' is Chunk.

## `chunkOverlap` (type: `integer`):

Tokens of text repeated from the end of one chunk at the start of the next, within a section.

## `outputFormat` (type: `string`):

Markdown keeps headings, lists and tables. Text is plain text (tables as tab-separated rows).

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

Pages to convert, for example '1-5, 8, 20-'. Leave empty for all pages.

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

Stop after this many pages of each PDF.

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

Auto reads pages that have no text layer (scans, photographed documents) with OCR. Off skips them. Force runs OCR on every page.

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

Languages in the scanned pages (up to 4).

## `includeTables` (type: `boolean`):

Turn ruled tables into Markdown tables.

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

Insert  comments in document Markdown, so you can cite page numbers.

## `saveMarkdownFiles` (type: `boolean`):

Also save each document as a .md file in the run's key-value store and add its download link (markdownFileUrl). Documents over 1 million characters are always saved this way.

## `maxPdfs` (type: `integer`):

Maximum number of PDFs to convert in this run.

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

Larger files are skipped (not charged).

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

Password for protected PDFs (used for all PDFs in the run).

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

PDFs converted at the same time. Raise it together with memory for large batches.

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

Optional. Most PDF hosts need no proxy.

## Actor input object example

```json
{
  "pdfUrls": [
    "https://www.irs.gov/pub/irs-pdf/fw9.pdf",
    "https://arxiv.org/abs/1706.03762"
  ],
  "maxPdfsPerPage": 20,
  "splitBy": "document",
  "chunkSize": 500,
  "chunkOverlap": 50,
  "outputFormat": "markdown",
  "maxPagesPerPdf": 500,
  "ocrMode": "auto",
  "ocrLanguages": [
    "eng"
  ],
  "includeTables": true,
  "includePageMarkers": false,
  "saveMarkdownFiles": false,
  "maxPdfs": 100,
  "maxFileSizeMb": 100,
  "maxConcurrency": 2,
  "proxyConfiguration": {
    "useApifyProxy": false
  }
}
```

# Actor output Schema

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

One row per document, page or chunk with Markdown or text, metadata and status.

## `summary` (type: `string`):

PDFs converted and failed, text pages and OCR pages.

# 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://www.irs.gov/pub/irs-pdf/fw9.pdf",
        "https://arxiv.org/abs/1706.03762"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("sonic_scraper/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 = { "pdfUrls": [
        "https://www.irs.gov/pub/irs-pdf/fw9.pdf",
        "https://arxiv.org/abs/1706.03762",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("sonic_scraper/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 '{
  "pdfUrls": [
    "https://www.irs.gov/pub/irs-pdf/fw9.pdf",
    "https://arxiv.org/abs/1706.03762"
  ]
}' |
apify call sonic_scraper/pdf-to-markdown --silent --output-dataset

```

## MCP server setup

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