# PDF to Markdown for RAG & LLM (`sequined_lacework/pdf-to-markdown-rag`) Actor

Convert PDF documents (URLs, arXiv, Google Drive) into clean Markdown with preserved tables and optional RAG-ready chunks. No browser, pay per page.

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

## Pricing

from $2.00 / 1,000 pages processed

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 for RAG & LLM

**PDF to Markdown for RAG** in one Apify Actor: send PDF links, get clean Markdown (headings, lists, tables), optional page markers and ready-to-embed text chunks. A fast **LLM PDF parser** that runs without a browser and charges per page.

### What it does

- Downloads PDFs from direct URLs, arXiv (`/abs/...` links are converted to `/pdf/...`) and Google Drive share links.
- Converts each PDF to Markdown with PyMuPDF / pymupdf4llm. **Extract tables from PDF to Markdown** tables keep their structure.
- Adds `--- Page N ---` markers (optional) so you can cite the source page.
- Optionally splits the Markdown into overlapping chunks for vector databases and RAG pipelines.
- Returns title, author, page counts, word count and a rough token estimate for every document.

### Why use it

- **Tables preserved**: tables are exported as Markdown tables instead of flattened text.
- **No browser**: pure Python PDF parsing, so runs are fast and cheap.
- **Cheap per-page pricing**: you pay only for pages that were converted.
- **LLM-ready output**: Markdown plus chunks, with token estimates to plan context windows.
- **Failures do not stop the run**: a bad URL produces an item with `status: "error"` and a short `error_message`.

### Input example

```json
{
    "urls": [
        "https://arxiv.org/pdf/1706.03762",
        "https://drive.google.com/file/d/FILE_ID/view?usp=sharing"
    ],
    "maxPagesPerDoc": 100,
    "chunkSize": 1500,
    "chunkOverlap": 200,
    "includePageMarkers": true,
    "maxFileSizeMb": 50,
    "maxConcurrency": 3
}
```

| Field | Default | Description |
|---|---|---|
| `urls` | demo arXiv PDF | PDF links (direct, arXiv, Google Drive) |
| `maxPagesPerDoc` | 100 | Convert only the first N pages (1-2000) |
| `chunkSize` | 0 | Chunk size in characters; 0 disables chunking (max 16000) |
| `chunkOverlap` | 200 | Overlap between chunks; reduced to `chunkSize / 4` if not smaller than `chunkSize` |
| `includePageMarkers` | true | Insert `--- Page N ---` before each page |
| `maxFileSizeMb` | 50 | Skip larger files (1-200) |
| `maxConcurrency` | 3 | PDFs processed in parallel (1-10) |

### Output example

One dataset item per URL (markdown and chunks truncated here):

```json
{
    "source_url": "https://arxiv.org/pdf/1706.03762",
    "resolved_url": "https://arxiv.org/pdf/1706.03762",
    "title": "Attention Is All You Need",
    "author": null,
    "total_pages": 15,
    "processed_pages": 15,
    "word_count": 6200,
    "estimated_tokens": 9800,
    "markdown": "--- Page 1 ---\n\n# Attention Is All You Need\n\n...\n\n| Model | BLEU |\n|---|---|\n| ... | ... |\n\n--- Page 2 ---\n\n...",
    "chunks": [
        "--- Page 1 ---\n\n# Attention Is All You Need\n\n...",
        "...end of the previous chunk. Start of the next chunk..."
    ],
    "status": "ok",
    "error_message": null
}
```

The numbers above are illustrative; real values depend on the document.

### Pricing

Pay-per-event: **$0.02 per run start** (the `run-started` event, charged once per run that has at least one URL) plus **$0.002 per page** (the `page-processed` event, one per converted page that produced text). Example: one run with a 100-page PDF costs $0.02 + 100 x $0.002 = **$0.22**. Failed downloads and empty (scanned) documents are not charged for pages; runs with no URLs are not charged at all.

The prices are not stored in the Actor code. `.actor/pay_per_event.json` documents the events and the suggested prices, but the real prices are set in Apify Console (Actor > Publication > Monetization).

### Use with Claude Desktop / Cursor (MCP)

Connect the Actor to any MCP client through the Apify MCP server: https://mcp.apify.com/?actors=sequined_lacework/pdf-to-markdown-rag

Add this to your Claude Desktop or Cursor MCP config (`mcpServers`):

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

An AI agent can pass PDF links (including arXiv and Google Drive) to the Actor and get Markdown with tables and page markers back, for example to read a paper or a contract before answering questions about it.

### Integrations: n8n and LangChain

#### n8n

Use the **Apify** node (operation: Run Actor, then Get Dataset Items) with the Actor ID `sequined_lacework/pdf-to-markdown-rag`, or an **HTTP Request** node (method `POST`, body type JSON) pointing at the synchronous endpoint, which returns the dataset items directly:

```
https://api.apify.com/v2/acts/sequined_lacework~pdf-to-markdown-rag/run-sync-get-dataset-items?token=<YOUR_APIFY_TOKEN>
```

Body:

```json
{
    "urls": ["https://arxiv.org/pdf/1706.03762"],
    "maxPagesPerDoc": 50,
    "chunkSize": 1500,
    "chunkOverlap": 200
}
```

Synchronous runs time out after 300 seconds, so use the regular run endpoint for large inputs.

#### LangChain (Python)

Install `langchain-apify` and `langchain-core`, and set the `APIFY_API_TOKEN` environment variable. The Markdown is in the `markdown` field and becomes the document `page_content`.

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

apify = ApifyWrapper()
loader = apify.call_actor(
    actor_id="sequined_lacework/pdf-to-markdown-rag",
    run_input={"urls": ["https://arxiv.org/pdf/1706.03762"], "maxPagesPerDoc": 50, "chunkSize": 1500},
    dataset_mapping_function=lambda item: Document(
        page_content=item["markdown"] or "",
        metadata={"source": item["source_url"], "title": item["title"], "pages": item["processed_pages"]},
    ),
)
docs = [d for d in loader.load() if d.page_content]
```

To load an existing run instead, use `ApifyDatasetLoader(dataset_id="<DATASET_ID>", dataset_mapping_function=...)` from `langchain_apify` with the same mapping function. If you set `chunkSize`, the `chunks` field already holds ready-to-embed pieces, so no extra text splitter is needed.

### Free plan limits

On the free Apify plan the Actor runs in demo mode:

- At most **5 PDF documents** per run; extra URLs are skipped.
- At most **10 pages per document** (the lower of 10 and `maxPagesPerDoc`).
- You are charged only for what was actually processed.

The run never fails because of these limits, and the log and status message say when something was skipped. Upgrade to a paid Apify plan to process the full input.

### Related Actors for RAG Pipelines

Build a complete RAG ingestion pipeline with the same clean Markdown output, chunking options and pay-per-event pricing:

- [PDF to Markdown for RAG & LLM](https://apify.com/sequined_lacework/pdf-to-markdown-rag) *(this Actor)*: PDFs (arXiv, Google Drive, any URL) with tables preserved
- [Website & Sitemap to Markdown for RAG & LLM](https://apify.com/sequined_lacework/website-to-markdown-rag): docs sites, blogs and sitemaps, code blocks preserved
- [Podcast RSS & Transcript Extractor for AI/RAG](https://apify.com/sequined_lacework/podcast-transcript-rag): podcast episodes with publisher transcripts
- [GitHub Repository to Clean Markdown for LLM & RAG](https://apify.com/sequined_lacework/github-repo-to-markdown): whole codebases as one Markdown context with a file tree
- [RSS, Atom & Substack to Clean Markdown for RAG](https://apify.com/sequined_lacework/rss-article-markdown): blogs and newsletters, full articles from teaser feeds

### Limits

- Default file size limit is 50 MB (configurable up to 200 MB).
- Scanned PDFs without a text layer produce empty Markdown. OCR is not included.
- Password-protected PDFs and links that need a login (HTML page instead of a PDF) return an error item.
- Very complex layouts (multi-column scientific papers, nested tables) may need manual review.

### FAQ

**Does it support Google Drive and arXiv links?**
Yes. Share links and `arxiv.org/abs/...` pages are converted to direct download links. Drive files must be shared with "anyone with the link".

**Which engine is used?**
pymupdf4llm on top of PyMuPDF. If it fails on a document, the Actor falls back to plain PyMuPDF text extraction with table detection.

**How are tokens estimated?**
Roughly 4 characters per token, which is a rough figure for English text. Use your model's tokenizer for exact counts.

**Can I process many files at once?**
Yes, pass many URLs and raise `maxConcurrency` (up to 10).

**Why is my output empty?**
The PDF is probably a scan without a text layer. Run OCR first.

**Do I need to do anything to run it locally?**
`pip install -r requirements.txt`, then `apify run` (Apify CLI). Local runs skip charging automatically.

# Actor input Schema

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

Direct links to PDF files. arXiv abstract links and Google Drive share links are converted automatically.

## `maxPagesPerDoc` (type: `integer`):

Only the first N pages of each PDF are converted (and charged).

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

If greater than 0, the Markdown is also split into RAG-ready chunks of at most this many characters. 0 disables chunking.

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

Approximate overlap between neighbouring chunks. Reduced automatically if not smaller than the chunk size.

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

Insert '--- Page N ---' before each page in the Markdown.

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

Files larger than this are skipped with an error.

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

How many PDFs are processed in parallel.

## Actor input object example

```json
{
  "urls": [
    "https://arxiv.org/pdf/1706.03762"
  ],
  "maxPagesPerDoc": 1,
  "chunkSize": 0,
  "chunkOverlap": 200,
  "includePageMarkers": true,
  "maxFileSizeMb": 50,
  "maxConcurrency": 3
}
```

# Actor output Schema

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

One item per input PDF with clean Markdown, metadata and optional RAG chunks.

# 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://arxiv.org/pdf/1706.03762"
    ],
    "maxPagesPerDoc": 1
};

// Run the Actor and wait for it to finish
const run = await client.actor("sequined_lacework/pdf-to-markdown-rag").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://arxiv.org/pdf/1706.03762"],
    "maxPagesPerDoc": 1,
}

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

```

## MCP server setup

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

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/H9niqWpv402nGuQuy/builds/yMjATKXTOtrZZe6A1/openapi.json
