# PDF → Markdown for RAG

Most RAG tutorials start after the text is already extracted. The PDF step is where things go wrong quietly. A scanned page gives you an empty string, your chunker accepts it, and the index fills with blanks.

This post shows one way to do the extraction step. You send a list of PDF links to an Apify actor, you get one row per file with the text split by page, and you know which pages were scans. I publish the actor on Apify as `cyrus_1`, so this is a tutorial from its author. I built it with an AI-assisted workflow: a small team of AI agents builds, tests and documents each actor, and I review and approve the result.

## The problem

A RAG pipeline needs three things from a PDF:

1. The text, split so you can chunk by page.
2. Some metadata (title, date, page count) to attach to each chunk.
3. A way to know when a page has no text, so you do not index nothing.

A PDF can be one of two kinds of file. Some have a text layer: the characters are in the file. Others are scans: the file holds a picture of a page. A text parser reads the first kind well and returns nothing for the second. One report can be both, for example a typed contract with a scanned signature page.

My design choice was to read the text layer first and say plainly which pages have none. Running OCR on every page would be slower and cost more, and most PDFs in a batch already carry their text.

## The actor

The actor is [PDF to Text and Markdown](https://apify.com/cyrus_1/pdf-to-text-markdown). You give it public PDF links. It gives you one JSON row per PDF with:

- `text` and `markdown` for the whole document
- a `pages` list with the text of each page
- metadata: title, author, dates, page count, file size
- `needsOcr` and `needsOcrPages`, which say which pages had no text layer

There is no login, no key for any other service and no proxy. You need an Apify account to run it.

## Input

This is the whole input for one file. It is the actor's default example, a public IRS form:

```json
{
  "urls": ["https://www.irs.gov/pub/irs-pdf/fw9.pdf"],
  "includeMarkdown": true,
  "includePages": true
}
```

Other ways to give it files:

- Several links in `urls`.
- Google Drive and Dropbox share links. They must be public ("anyone with the link"). A Drive folder link is refused. A Dropbox folder link is downloaded as a ZIP.
- A ZIP of PDFs.
- A TXT or CSV file that lists links (`urlListUrls`).
- A web page that links to PDFs (`followPdfLinks: true`). It reads that page for links ending in `.pdf`, one level deep.
- An Apify dataset with a link field, or files in a key-value store.

It does not take a private folder or a link that needs a login. Those come back as error rows.

## Output

This is one row from a real run on that IRS form. I cut the text and kept page 1 of 6:

```json
{
  "rowType": "document",
  "url": "https://www.irs.gov/pub/irs-pdf/fw9.pdf",
  "status": "ok",
  "title": "Form W-9 (Rev. March 2024)",
  "pageCount": 6,
  "pagesProcessed": 6,
  "needsOcr": false,
  "needsOcrPages": [],
  "charCount": 38049,
  "text": "Form  W-9\n\n(Rev. March 2024)\nDepartment of the Treasury …",
  "markdown": "Form  W-9\n\n(Rev. March 2024) Department of the Treasury …",
  "pages": [
    {
      "page": 1,
      "text": "Form  W-9\n\n(Rev. March 2024)\nDepartment of the Treasury …",
      "charCount": 5778,
      "needsOcr": false
    }
  ],
  "charges": { "pdf": 1 }
}
```

A file that fails gives a row with `rowType: "error"`, an `errorCode` such as `http_error`, `too_large`, `corrupt_pdf` or `encrypted`, and a plain message. Error rows are free. One bad link does not stop the rest of the list.

A word on the Markdown. It is a best-effort guess. Headings come from font size, lists from bullet characters, paragraphs from line joins. Tables come back as lines of text, not Markdown tables. Pages with several columns are read in the order the PDF library finds them. The `markdown` field in the sample above is mostly flowing text. If your documents are table-heavy, test a few before you commit.

## Call it from Python

Install the client with `pip install "apify-client>=3.5"`. Put your token in an environment variable, not in the file.

```python
import os
from apify_client import ApifyClient

client = ApifyClient(os.environ["APIFY_TOKEN"])

run = client.actor("cyrus_1/pdf-to-text-markdown").call(
    run_input={"urls": ["https://www.irs.gov/pub/irs-pdf/fw9.pdf"]}
)

for row in client.dataset(run.default_dataset_id).iterate_items():
    if row["rowType"] == "error":
        print("failed:", row["url"], row["errorCode"])
        continue
    print(row["title"], row["pageCount"], "needs OCR:", row["needsOcr"])
```

For the IRS form this prints the title `Form W-9 (Rev. March 2024)`, `6`, and `needs OCR: False`.

## Chunk by page for RAG

This part is plain Python and does not depend on the actor. It turns each page into one chunk with metadata and skips pages that have no text.

```python
def page_chunks(row):
    """Yield one dict per page that has text."""
    for page in row.get("pages") or []:
        text = (page.get("text") or "").strip()
        if not text:
            continue  # a scan with no text layer: do not index an empty string
        yield {
            "text": text,
            "source": row["url"],
            "title": row.get("title"),
            "page": page["page"],
        }

chunks = []
for row in client.dataset(run.default_dataset_id).iterate_items():
    if row["rowType"] == "document":
        chunks.extend(page_chunks(row))

print(len(chunks), "chunks")
```

From here you embed `chunks` with whatever model you use. The `source` and `page` fields let you cite the page in an answer.

## The same call from JavaScript

Save it as `run.mjs` (it uses `import` and top-level `await`) and run it with `node run.mjs`.

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

const client = new ApifyClient({ token: process.env.APIFY_TOKEN });

const run = await client.actor("cyrus_1/pdf-to-text-markdown").call({
  urls: ["https://www.irs.gov/pub/irs-pdf/fw9.pdf"],
});

const { items } = await client.dataset(run.defaultDatasetId).listItems();
for (const row of items) {
  console.log(row.rowType, row.title ?? row.errorCode, row.pageCount ?? "");
}
```

## What it costs per 1,000 PDFs

Prices from the actor's README:

| What | Price |
| --- | --- |
| A PDF with a text layer, up to 20 pages | $4 per 1,000 PDFs ($0.004 each) |
| Each page past 20 in the same PDF | $0.30 per 1,000 pages |
| A PDF with no text layer (OCR off), a failed download, any error row | free |
| Apify run-start charge | very small, shown on the Pricing tab |

Worked examples from the README:

- 1,000 PDFs of 20 pages or fewer: $4.00.
- One 200-page report: $0.004 + 180 x $0.0003 = $0.058. So $5 covers about 86 of those.
- Apify's free plan includes $5 of credit a month. That is about 1,250 PDFs of up to 20 pages.

To cap spending, set a maximum cost per run in the run options. The actor stops cleanly when it reaches it.

## What about scanned pages?

By default the actor reads only the text layer. A page with no text comes back with `needsOcr: true`, and a PDF that is all scans is free. That is on purpose: you find out which files are scans before you spend money on them.

If you want those pages read, set `ocrScannedPages` to true:

```json
{
  "urls": ["https://example.com/your-scanned-contract.pdf"],
  "ocrScannedPages": true,
  "ocrLanguage": "en"
}
```

What the option does:

- The scanned pages are read by OCR in the same run and merged into the same row, in page order. There is no second actor to call.
- It costs $4 per 1,000 scanned pages where OCR finds text. A page where OCR finds nothing, or fails, is free.
- A PDF made only of scans is charged for its OCR pages and not for the `pdf` event on top. A 5-page scan costs $0.020. A 10-page scanned contract costs $0.040, so $5 covers 125 of them.
- A mixed PDF pays the normal price for its text pages, plus each OCR page.
- `ocrMaxPagesPerPdf` (default 20) caps how many scanned pages of one file are read, so one huge scan cannot surprise you.
- It needs 1024 MB of memory. With less, the run stops at the start with a clear message.
- `ocrLanguage` can be `en`, `ch`, `korean`, `arabic`, `cyrillic`, `devanagari`, `th`, `el`, `ta` or `te`. For Arabic script the text comes back in reading order.
- Each OCR page carries an `ocrConfidence`, so you can drop weak pages before indexing.

The limits, as the README states them. OCR is imperfect. Low resolution, handwriting, heavy skew and dense small print cause errors. Tables on scanned pages are not rebuilt. OCR pages come back as plain text, with no headings or lists. I do not show OCR output in this post, so test the option on a few of your own scans and read the results before you rely on it.

If most of your files are scans or photos, the companion actor [Image OCR](https://apify.com/cyrus_1/image-ocr-text-extractor) is the better fit. It gives word boxes, accurate mode and Japanese. It also reads PDF pages that already have a text layer straight from that layer, at $1 per 1,000 pages instead of $4, and only runs OCR on the rest.

## Three things that trip people up

- **A scan gives an empty page, not an error.** The text is an empty string and `needsOcr` is `true`. Filter on that before you chunk, as the code above does.
- **Very long documents make very large rows.** A 500-page book is a few MB of text, and Apify limits one dataset item to 9 MB. For long documents, set `includePages` to `false`.
- **Some links are not files.** A Drive folder link is refused. A Drive link to a very large file can return a virus-scan page instead of the file. Both give a free error row, so check for `rowType: "error"` in your loop.

## Limits

- Public links only. Password-protected PDFs are not opened (`errorCode: encrypted`).
- 50 MB per file and 500 pages per file by default. You can change both.
- No proxy. A site that blocks Apify's servers gives a free error row.
- Nothing is stored after the run except the output dataset in your own account.

## Try it

The actor is at <https://apify.com/cyrus_1/pdf-to-text-markdown>. Run it with the default input first. It reads one public IRS form and costs a fraction of a cent.

One question for you: how do you handle tables and multi-column pages before chunking? The actor returns them as lines of text, and I would like to hear what works for others.

\*Disclosure: I wrote this with help from AI tools. The numbers come from the actor's README and from real runs, and the code uses the official `apify-client`.
