DEV Community

ben-gs-ai
ben-gs-ai

Posted on Originally published at github.com

Convert PDF to Markdown for RAG

This guide turns a PDF link into text you can chunk and cite, with a page number on every page. You send a URL to an Apify Actor and get back one row per file: the whole document as markdown, plus a pages list where each entry has a pageNumber and its text. No API key for a model is needed.

Why this way

A RAG pipeline needs two things from a PDF: clean text to split, and a way to point back to the source. Plain text extraction usually gives you the first and loses the second. Here the page list comes with the text, so every chunk you build can carry the page it came from, and your answers can say "page 6" instead of just naming the file.

Other points from the Actor's own README:

  • It makes no model calls, so the same file gives the same result every time.
  • A scanned PDF page with no text layer is read with OCR automatically, and only that page. OCR is English only.
  • Every file gets a status. Check it before you index anything.
  • You pay only for a file that returns text. A 404, a bot check, a damaged file or a password-protected file is a free row with a message saying why.

One limit to know up front: PDF tables come back as text lines in reading order, not rebuilt as Markdown tables. Word, Excel and HTML tables do become real Markdown tables.

Steps

1. The input

This is the exact input used for the run shown below. The file is a PDF on arXiv. maxOcrPages caps OCR work per file at 2 pages (the default is 10).

{
  "urls": [
    {
      "url": "https://arxiv.org/pdf/1706.03762"
    }
  ],
  "maxOcrPages": 2
}
Enter fullscreen mode Exit fullscreen mode

2. Call it with curl

curl -X POST \
  "https://api.apify.com/v2/acts/goldensky_api~pdf-document-to-markdown/run-sync-get-dataset-items?token=YOUR_APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"urls":[{"url":"https://arxiv.org/pdf/1706.03762"}],"maxOcrPages":2}'
Enter fullscreen mode Exit fullscreen mode

3. Call it with Python

from apify_client import ApifyClient

client = ApifyClient("YOUR_APIFY_TOKEN")

run = client.actor("goldensky_api/pdf-document-to-markdown").call(
    run_input={
        "urls": [{"url": "https://arxiv.org/pdf/1706.03762"}],
        "maxOcrPages": 2,
    }
)

for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    if item["status"] != "success":
        print(item["url"], item["status"], item["message"])
        continue
    for page in item["pages"]:
        # one chunk source per page, with its citation
        print(page["pageNumber"], page["text"][:80])
Enter fullscreen mode Exit fullscreen mode

4. Call it with JavaScript

import { ApifyClient } from 'apify-client';

const client = new ApifyClient({ token: 'YOUR_APIFY_TOKEN' });

const run = await client.actor('goldensky_api/pdf-document-to-markdown').call({
  urls: [{ url: 'https://arxiv.org/pdf/1706.03762' }],
  maxOcrPages: 2,
});

const { items } = await client.dataset(run.defaultDatasetId).listItems();
for (const item of items) {
  if (item.status !== 'success') {
    console.log(item.url, item.status, item.message);
    continue;
  }
  for (const page of item.pages) {
    console.log(page.pageNumber, page.text.slice(0, 80));
  }
}
Enter fullscreen mode Exit fullscreen mode

To chunk with citations, split each pages[].text on its own and store url and pageNumber as metadata next to every chunk. Use markdown instead when you want the whole document in one string.

What comes back

The run returned one item, for a PDF: the paper "Attention Is All You Need" (arXiv 1706.03762). It has 15 pages and 6,102 words. It has a text layer, so ocrPages is 0 and OCR never ran. Long text is cut with ... here; the real fields hold the full text.

{
  "url": "https://arxiv.org/pdf/1706.03762",
  "fileName": "1706.03762v7.pdf",
  "status": "success",
  "message": null,
  "format": "pdf",
  "pageCount": 15,
  "wordCount": 6102,
  "charCount": 39786,
  "ocrPages": 0,
  "markdown": "Provided proper attribution is provided, Google hereby grants permission to\nreproduce the tables and figures in this paper solely for use in journalistic or\nscholarly works.\n\nAttention Is All You Need\n\nAshish Vaswani\n...",
  "pages": [
    {
      "pageNumber": 1,
      "text": "Provided proper attribution is provided, Google hereby grants permission to\nreproduce the tables and figures in this paper solely for use in journalistic or\nscholarly works.\n\nAttention Is All You Need\n..."
    },
    {
      "pageNumber": 2,
      "text": "1 Introduction\n\nRecurrent neural networks, long short-term memory [13] and gated recurrent [7] neural networks\nin particular, have been firmly established as state of the art approaches in sequence modeling and\n..."
    },
    {
      "pageNumber": 6,
      "text": "Table 1: Maximum path lengths, per-layer complexity and minimum number of sequential operations\nfor different layer types. n is the sequence length, d is the representation dimension, ...\n..."
    }
  ],
  "truncated": false,
  "httpStatus": 200,
  "finalUrl": "https://arxiv.org/pdf/1706.03762",
  "charged": true,
  "units": 1,
  "notes": [],
  "processedAt": "2026-12-03T19:04:53.092Z"
}
Enter fullscreen mode Exit fullscreen mode

Three things to notice. The text is what the PDF stores, so headings such as "1 Introduction" appear as plain lines rather than Markdown # headings. Page 6 holds Table 1, and it arrives as text lines, as the README warns. Figure labels on the last pages come through as scattered words. Plan a small cleanup step if your sources have many figures or tables.

Cost

The README lists $0.003 per document on the Free and Bronze tiers, $0.0026 on Silver and $0.0021 on Gold. A 100-page text PDF costs one document, so page count does not change the price. Scanned pages add one document for every 5 OCR pages.

  • This run: one PDF, no OCR pages, units: 1. That is $0.003.
  • 1,000 results: 1,000 text PDFs cost $3.00 at $0.003, $2.60 at $0.0026 or $2.10 at $0.0021. Any scanned pages in the batch add to this at one document per 5 OCR pages, and failed files add nothing.

Next

  • Run a batch: pass many links in urls. maxDocuments (default 100) limits files per run, and extra files are skipped without charge.
  • Use the same call for Word, PowerPoint, Excel, EPUB and HTML files. Slides, sheets and chapters come back as pages, so the same citation approach works.

Run it on Apify

Top comments (0)