# PDF to Markdown for LLMs and RAG, with OCR (`bitbotboo/pdf-to-markdown-for-llms`) Actor

PDF to Markdown for RAG and LLMs. Keeps headings, lists and tables, reads columns in order, and OCRs scanned pages. Give it public PDF links or saved PDF files, get Markdown back. Pay per page processed, no monthly fee.

- **URL**: https://apify.com/bitbotboo/pdf-to-markdown-for-llms.md
- **Developed by:** [sudo nz](https://apify.com/bitbotboo) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.50 / 1,000 text page converteds

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

This Actor turns PDFs into clean **PDF to Markdown** output for RAG pipelines, AI agents and LLM prompts. Give it public PDF links, or PDF files you saved in a key-value store, and you get structured Markdown back: headings as `#` lines, lists, tables as Markdown tables, columns in reading order for simple layouts, and no page numbers or running headers. Pages that are only an image of text (scans) are read with built-in OCR. You pay per page processed, with no monthly fee.

### Sample: input and output

The prefilled input converts a real public document, IRS Publication 594 (8 pages, text layer, no scan). Press **Start** and you get this.

Input:

```json
{ "pdfUrls": [{ "url": "https://www.irs.gov/pub/irs-pdf/p594.pdf" }] }
```

The start of the `markdown` field in the dataset item (copied from a real run, cut after the third section heading; nothing edited):

```markdown
## The IRS Collection Process

#### Publication 594

This publication provides a general description of the IRS collection process. The collection process is a series of actions that the IRS can take to collect the taxes you owe if you don’t voluntarily pay them. The collection process will begin if you don’t make your required payments in full and on time, after receiving your bill.

Please keep in mind that this publication is for information only, and may not account for every tax collection scenario. It’s also not a technical analysis of tax law and does not include a detailed explanation of your rights. For an explanation of your rights, please see Publication 1, Your Rights as a Taxpayer.

### If you have questions or need help

Please visit IRS.gov for your tax needs. You can get answers to your tax questions from the Interactive Tax Assistant www.irs.gov/ITA. You can also check www.irs.gov/forms-instructions to find all the IRS tax forms and publications mentioned here and the IRS video portal at www.irs.gov/newsroom/videos to view informational videos on a variety of topics in this publication.
```

The rest of the item for this document: `status` `ok`, `pageCount` 8, `pagesProcessed` 8, `ocrPages` 0, `characterCount` 59,796, `approxTokenCount` 14,949 (an estimate), `warnings` empty.

### Pricing examples

You pay one fee for each document plus a fee for each page that produced text. A scanned page read with OCR costs more. These are the prices in the Pricing section below, before the small Actor start fee (US$0.0001 at the default 2 GB of memory).

| Document | Arithmetic | Cost |
|---|---|---|
| The 8-page sample above (text) | 0.002 + 8 x 0.0005 | **US$0.006** |
| 10-page text PDF | 0.002 + 10 x 0.0005 | **US$0.007** |
| 50-page text report | 0.002 + 50 x 0.0005 | **US$0.027** |
| 20-page scan, OCR finds text on every page | 0.002 + 20 x 0.010 | **US$0.202** |

A page with no text, a failed file and a refused file are not charged. Mixed files are in the Pricing section.

### What you get

- **Headings that mean something.** Heading levels come from the font sizes in the document, so you can split the Markdown by section before you embed it.
- **Tables.** Tables drawn with ruling lines, tables whose header row is ruled but whose rows are not (common in financial statements), and plain-text tables whose columns line up, become Markdown tables. Tables with merged cells, tables turned sideways, and tables inside boxes or sidebars can come out as plain text or with cells in the wrong place.
- **Simple two-column pages in order.** Pages such as papers and reports, including a full-width title or box above the columns, come out left column then right column. Pages that mix several boxes, sidebars or three or more columns (newsletters and fact sheets) may still have lines mixed between columns; on two real examples most of the text was in order but not all.
- **Lists, paragraphs, hyphenated line ends** joined into normal paragraphs; repeated headers, footers and page numbers removed. Text turned sideways in a margin (a scan stamp, a journal's side label) is left out of the body.
- **OCR for scans**, automatically and only on pages that have almost no text layer (fewer than 25 characters), so text PDFs stay cheap and fast. A scanned page that already carries a printed or stamped line of text (a court header, "Downloaded from ...") counts as a text page: set **OCR for scanned pages** to `force` for such files. Models for Latin-alphabet languages (English, French, German, Spanish and others), Chinese, Korean and Cyrillic are built in.
- **One result per document or per page.** Page mode gives one dataset item per page, ready for chunking and embedding.
- **A bad file never stops the run.** A damaged, password-protected or unreachable PDF produces an error item with a clear code, and the rest carry on. One protection: a run stops early, with a message that says why, after 20 files in a row that fail or give no text, or after 10 minutes of work you are not charged for (failed files, files with no text, reading address lists, and time on a file beyond a generous allowance for the pages it was charged). A run reads at most 5 address lists. Everything converted before that is saved and charged.

### How to use it

1. Paste PDF addresses (http or https) into **PDF addresses**, or list the record keys of files in a key-value store.
2. Leave **OCR** on Auto, or switch it off to never pay for OCR pages.
3. Run it, and read the Markdown from the dataset, as JSON, CSV, Excel or through the API.

#### Input

| Field | What it does | Default |
|---|---|---|
| `pdfUrls` | PDF addresses. Only http and https. Private and internal network addresses are refused. You can also upload a text file with one address per line (up to 1,000 are read). | |
| `keyValueStoreKeys`, `keyValueStore` | Keys of PDF files in a key-value store. Pick the store that holds your files in the `keyValueStore` field (in the API, give the store's ID); picking it is what lets the Actor read it. If you leave it empty the Actor looks in the run's own default store, which starts empty. | |
| `pageStart`, `pageEnd` | Convert only this page range. | whole file |
| `ocrMode` | `auto` (OCR only pages with almost no text), `off`, or `force` (OCR every page). | `auto` |
| `ocrLanguage` | `latin`, `chinese`, `korean`, `cyrillic`. | `latin` |
| `outputGranularity` | `document` or `page`. | `document` |
| `includePages` | In document mode, also return a `pages` list. | off |
| `tablesAsMarkdown` | Markdown tables, or tab-separated lines. | on |
| `maxPages` | Safety cap per document. | 300 |
| `maxFileSizeMb` | Files larger than this are skipped. | 50 |

#### Output example

```json
{
  "source": "https://www.census.gov/content/dam/Census/library/publications/2023/demo/p60-279.pdf",
  "status": "ok",
  "title": "Income in the United States: 2022",
  "pageCount": 62,
  "pagesProcessed": 12,
  "markdown": "# Income in the United States: 2022\n\n### Current Population Reports\n\nBy Gloria Guzman and Melissa Kollar Issued September 2023\n\nP60-279\n\nAcknowledgments The Social, Economic, and Housing Statistics Division of the U.S. Census Bureau recognizes ...",
  "looksScanned": false,
  "ocrPages": 0,
  "tablesFound": 4,
  "characterCount": 35264,
  "approxTokenCount": 8816,
  "warnings": [],
  "processingTimeSeconds": 3.4
}
```

This is a real result (Last page set to 12; the `markdown` text is cut short here). The source is a public report of the U.S. Census Bureau.

`approxTokenCount` is characters divided by four, an estimate for English text, not a tokenizer count. A failed file gives `"status": "error"` and an `error` object with a `code` and a message. The codes are:

| Code | Meaning |
|---|---|
| `ENCRYPTED` | The PDF is password-protected. |
| `BROKEN_PDF` | The file is damaged or is not a PDF. |
| `ADDRESS_NOT_ALLOWED` | The address is not a public http or https address. |
| `DOWNLOAD_FAILED` | The download failed, was too large or took too long. |
| `PDF_ERROR` | The PDF could not be read. |
| `UNEXPECTED_ERROR` | Any other fault. |

None of these is charged. When a run stops early (see "A bad file never stops the run" above), the last dataset item has `"status": "stopped"` and an `error` with the code `UNBILLED_LIMIT`; its message says how many documents were not processed. If you filter on `status`, expect `ok`, `error` and `stopped`. If a document's Markdown is too large for one dataset item (about 8 MB), `markdown` is null and `markdownRecordUrl` links to a record in the run's key-value store that holds it; a warning says so.

### Pricing

You pay for pages that produced text, plus a small fee per document, and only after the result is saved.

| Event | Price | Per 1,000 |
|---|---|---|
| Actor start (set by Apify) | $0.00005 for each GB of memory | |
| Document processed | $0.002 | $2.00 |
| Text page | $0.0005 | $0.50 |
| OCR page (scanned) | $0.010 | $10.00 |

**What is not charged:** a failed or refused file; a failed page; a page with no text (blank, drawing, or nothing found by OCR); a page whose OCR took longer than 60 seconds (it comes back with a warning; the first OCR page of each language may take up to 120 seconds, because the model loads then, and it is charged if it finishes); a text page that held only running headers or page numbers. **What is charged as an OCR page:** a page with no text layer, including an image-only page, when OCR returns text from it.

The Actor start fee is charged once for each run and is not in the examples below. At the default 2 GB of memory it is $0.0001.

Examples, so you can check your bill:

- 20-page text PDF: 0.002 + 20 x 0.0005 = **$0.012**.
- 10-page scanned PDF where OCR reads text on every page: 0.002 + 10 x 0.010 = **$0.102**.
- 10-page PDF with 8 text pages and 2 scanned pages with text: 0.002 + 8 x 0.0005 + 2 x 0.010 = **$0.026**.
- The same 10-page PDF if one of the scanned pages is blank and OCR finds nothing: 0.002 + 8 x 0.0005 + 1 x 0.010 = **$0.016**.
- 1,000 single-page text PDFs: 1,000 x (0.002 + 0.0005) = **$2.50**.

Set a maximum cost per run and the Actor stops when the next page would pass it, and keeps the pages it has done. Charges for a document are made after its result is saved to the dataset.

### Speed and quality, measured

The numbers below come from 17 real PDFs the Actor was not built on (government reports, standards, papers, a financial statement, slides, newsletters, scans, Spanish and Chinese). "Word recall" is the share of the words in each page's own text layer that appear in the Markdown, page by page.

- Typical text PDFs (reports, standards, datasheets, slides, papers): word recall 0.89 to 1.00, text pages about 0.07 seconds each on a fast machine.
- Hardest: forms with boxed fields (an IRS 1040: recall 0.94, order jumbled), newsletters and fact sheets with boxes and mixed columns (order partly wrong), three-column pages, tables inside sidebars, and drawings or maps (no text to return).
- OCR on a real typed scan was accurate. On the Apify platform at 2 GB, an OCR page takes about 8 seconds on a sparse scan and up to 43 seconds on a page full of dense text. A document is processed for about 10 minutes at most, so a scan of dense pages may stop after about 14 pages, with a warning. The pages done are kept and charged. Use **First page** and **Last page** to split a long scan across runs.

### Limits

- Forms with boxed fields, such as tax forms, come out with jumbled order and words split across cells. Documents with a real reading flow work best.
- Tables with merged cells or nested tables are not recovered, and a framed box of text can be mistaken for a table. Three or more columns on a page are not handled, and pages that mix columns with several boxes may have lines out of order.
- Long dot leaders in tables of contents are kept, and page numbers or figure labels in a larger font can become headings.
- OCR is for printed text. Handwriting, very low resolution or skewed scans will give poor results. OCR reads whole lines, so a scanned table is returned as lines of text.
- Password-protected PDFs are refused with a clear error. Equations and images are not described.
- Maximum 300 pages per document by default (up to 2,000) and 50 MB per file (up to 200 MB). A document is processed for about 10 minutes at most, and a download for at most 2 minutes. OCR of a single page is stopped after 60 seconds (that page is returned with a warning and not charged); the first OCR page of each language gets up to 120 seconds, because the model loads then.
- Only public addresses are fetched. Up to 5 redirects are followed, and each one is checked again. The user agent is `PDFToMarkdownActor/1.0`.

### Use it from code and AI agents

Every run is billed to your Apify account. Set `APIFY_TOKEN` first (Apify Console, Settings, API & Integrations). The examples need Python 3.11 or later.

**Python** (`pip install apify-client`, Python 3.11 or later):

```python
import os
from apify_client import ApifyClient

client = ApifyClient(os.environ["APIFY_TOKEN"])
run = client.actor("bitbotboo/pdf-to-markdown-for-llms").call(run_input={
    "pdfUrls": [{"url": "https://www.irs.gov/pub/irs-pdf/p594.pdf"}],
    "outputGranularity": "page",  # one item per page, ready to chunk
})
for item in client.dataset(run.default_dataset_id).iterate_items():
    if item["status"] == "ok":
        print(item["markdown"][:200])
```

**LangChain** (`pip install langchain-apify`; uses the `ApifyWrapper` pattern from Apify's LangChain page):

```python
from langchain_apify import ApifyWrapper
from langchain_core.documents import Document

loader = ApifyWrapper().call_actor(
    actor_id="bitbotboo/pdf-to-markdown-for-llms",
    run_input={"pdfUrls": [{"url": "https://www.irs.gov/pub/irs-pdf/p594.pdf"}],
               "outputGranularity": "page"},
    dataset_mapping_function=lambda item: Document(
        page_content=item.get("markdown") or "", metadata={"source": item["source"], "page": item.get("page")}
    ),
)
documents = [d for d in loader.load() if d.page_content]  # skips blank pages and failed files
```

**LlamaIndex** (`pip install apify-client llama-index-core llama-index-readers-apify`, in a virtual environment of its own: this reader needs apify-client 1.x, and the two examples above need the current version):

```python
import os
from llama_index.core import Document
from llama_index.readers.apify import ApifyActor

reader = ApifyActor(os.environ["APIFY_TOKEN"])
documents = reader.load_data(
    actor_id="bitbotboo/pdf-to-markdown-for-llms",
    run_input={"pdfUrls": [{"url": "https://www.irs.gov/pub/irs-pdf/p594.pdf"}],
               "outputGranularity": "page"},
    dataset_mapping_function=lambda item: Document(
        text=item.get("markdown") or "", metadata={"source": item["source"], "page": item.get("page")}
    ),
)
documents = [d for d in documents if d.text]  # skips blank pages and failed files
```

**AI agents (MCP).** Add Apify's MCP server with this Actor selected. In a client that supports OAuth, add the address and sign in to Apify when asked:

```
https://mcp.apify.com?tools=bitbotboo/pdf-to-markdown-for-llms
```

If your client has no OAuth, send your token in an `Authorization: Bearer <APIFY_TOKEN>` header, and do not commit a config file that holds it.

### Questions and answers

**Does it send my documents to another service?** No. Everything runs inside the Actor. No third-party API is called except to download the PDF addresses you give it.

**Where do my files and results go?** A PDF is held in the memory of the run only. The Actor does not save it. The results go to the dataset (and, for a very large document, the key-value store) of your own run, and Apify keeps them for as long as your plan allows. The Actor does not send your files or results to its owner. If you share a run with the developer (an Apify privacy setting, or a run link in an issue), the developer can see that run's input, log and results.

**How do I use it with LangChain, LlamaIndex or my own pipeline?** Run it through the Apify API or an integration, and read the `markdown` field. Use page mode to get one item per page. Examples are in "Use it from code and AI agents" above.

**Why is a scanned PDF slower and dearer?** OCR needs far more computing than reading a text layer, and a page without a text layer has to be read as an image.

**Can I make sure I never pay for OCR?** Yes: set OCR to Off. Scanned pages then come back empty with a warning.

**Something came out wrong. What do I do?** Open an issue from the Actor page with the PDF address if it is public, and the page number.

# Actor input Schema

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

Public http or https addresses of the PDF files to convert. Type one per line, or upload a text file with one address per line (blank lines and lines starting with # are ignored; at most 1,000 addresses are read from a file, and at most 5 such files per run). Private and internal network addresses are refused. Example: https://www.irs.gov/pub/irs-pdf/p594.pdf. Use this field or keyValueStoreKeys, or both.

## `keyValueStoreKeys` (type: `array`):

Record keys of PDF files you saved in a key-value store, for files that have no public address. Allowed values: a list of key names, one per line. Default: empty. Example: my-report. Use together with keyValueStore. Leave empty if you give addresses.

## `keyValueStore` (type: `string`):

The key-value store that holds the PDF files named in keyValueStoreKeys. Picking it here is what gives the Actor permission to read it. In the API, give the store's ID. Default: empty, which means the run's own default store, and that starts empty, so set this field whenever you use keyValueStoreKeys.

## `pageStart` (type: `integer`):

First page to convert. Whole number, 1 or more; 1 is the first page of the document. Default: 1. Example: 3 starts at page 3. Applies to every document in the run.

## `pageEnd` (type: `integer`):

Last page to convert. Whole number, 1 or more. Default: empty, which converts to the end of the document. Example: 12 stops after page 12. Applies to every document in the run.

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

Controls OCR (reading text from page images). Allowed values: auto, off, force. auto: OCR only pages that have almost no text layer (fewer than 25 characters), so text PDFs stay cheap. off: never OCR; scanned pages come back empty with a warning and are not charged. force: OCR every page, which costs more; use it when the text layer is garbled, or when a scanned page carries a printed or stamped line of text (auto reads such a page as a text page). Default: auto.

## `ocrLanguage` (type: `string`):

Script of the text on scanned pages, used only when OCR runs. Allowed values: latin (English, French, German, Spanish, Italian, Portuguese, Dutch and other Latin-alphabet languages), chinese, korean, cyrillic (Russian, Ukrainian and others). Default: latin. Example: chinese for a scanned Chinese report.

## `outputGranularity` (type: `string`):

How the result is split into dataset items. Allowed values: document, page. document: one item per PDF, with the whole Markdown in the markdown field. page: one item per page, ready for chunking and embedding. Default: document.

## `includePages` (type: `boolean`):

Only used when outputGranularity is document. true: each item also has a pages list with the Markdown of each page. false: the item has the whole-document Markdown only. Default: false.

## `tablesAsMarkdown` (type: `boolean`):

How tables are written. true: tables become Markdown tables. false: tables come out as tab-separated lines. Default: true.

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

Safety cap on the number of pages converted from one document. Whole number from 1 to 2000. Pages beyond the cap are skipped and a warning is added to the item. Default: 300. Example: 50.

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

Largest PDF file to accept, in megabytes. Whole number from 1 to 200. A larger file is not downloaded or processed and gives an error item. Default: 50. Example: 20.

## Actor input object example

```json
{
  "pdfUrls": [
    {
      "url": "https://www.irs.gov/pub/irs-pdf/p594.pdf"
    }
  ],
  "pageStart": 1,
  "ocrMode": "auto",
  "ocrLanguage": "latin",
  "outputGranularity": "document",
  "includePages": false,
  "tablesAsMarkdown": true,
  "maxPages": 300,
  "maxFileSizeMb": 50
}
```

# Actor output Schema

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

Dataset items from this run. Each item holds the source, the status, the Markdown and the other fields listed in the dataset schema. An item that could not be converted has status error and an error code and message.

# 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": [
        {
            "url": "https://www.irs.gov/pub/irs-pdf/p594.pdf"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("bitbotboo/pdf-to-markdown-for-llms").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": [{ "url": "https://www.irs.gov/pub/irs-pdf/p594.pdf" }] }

# Run the Actor and wait for it to finish
run = client.actor("bitbotboo/pdf-to-markdown-for-llms").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": [
    {
      "url": "https://www.irs.gov/pub/irs-pdf/p594.pdf"
    }
  ]
}' |
apify call bitbotboo/pdf-to-markdown-for-llms --silent --output-dataset

```

## MCP server setup

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

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/SIkUabf2Yd6guN8Hi/builds/vVNfCxAIBRxlUVEte/openapi.json
