Helenis API
Start for free

Documents & mediaPDF

PDF to Text API: Digital and Scanned PDFs to Clean Text and Markdown

PDF to text API tutorial: extract digital PDFs from their text layer, OCR scanned pages and rebuild tables as Markdown for RAG, with Python and real output.

PDF to Text API cover: a document sticker, an arrow and a JSON response with page_count 15, pages_extracted 1, ai_pages 1, method ai and the producer pdfTeX-1.40.25.
Table 2 of the Transformer paper read by the AI: one page, 20 credits, a real Markdown table.

Most document pipelines start with the same line of code: open the PDF, extract the text. It works on the first test file, then the real corpus arrives. A two-column paper comes back with its columns interleaved, a results table becomes a run of numbers with no columns, 10^20 turns into 1020, and part of the archive returns an empty string because those pages are scans.

A PDF to text API is worth calling when it handles all of these cases without you sorting the files first. This article runs the PDF to Text API on three real documents: a digital research paper read from its own text layer for one credit, a results table rebuilt as Markdown by the AI, and scanned book pages read by OCR. Every JSON response below comes from a real call.

What a PDF actually stores, and why extraction goes wrong

A PDF is a page-description format. It does not store paragraphs, columns or tables; it stores instructions to draw glyphs at given positions. Libraries such as pypdf or pdfminer.six rebuild text by grouping those glyphs into lines and guessing a reading order. That guess is where the familiar problems come from:

  • Tables lose their grid. A cell is text drawn at some x position; empty cells leave no trace, so values shift columns.
  • Layout becomes characters. Flattened superscripts turn 10^20 into 1020; line-end hyphens stay; columns can interleave.
  • Scans have no text at all. Scanned pages are only images, so the extraction is empty.
  • Some scans have a bad text layer. Many scanners add an invisible OCR layer, of whatever quality their software managed.

The usual answer is a stack of tools plus code to route each file. A vision model reads any page, but sending a 300-page digital report to one pays for text that was already there.

Approach Digital pages Scanned pages Tables Cost per page
Text-layer library (pypdf, pdfminer.six) Exact characters, guessed order Empty Flattened CPU only
Classic OCR (Tesseract) Works, slower than reading the layer Yes, printed text Flattened CPU only
Vision model on every page Clean reading order Yes, handwriting included Rebuilt AI price on every page
This API, auto mode Text layer AI OCR Flattened AI price on scans only
This API, ai mode AI with the native text AI OCR Markdown tables AI price on every page

Three modes, one response

POST /v1/pdf/extract takes a JSON body with a url; POST /v1/pdf/extract/upload takes a multipart file. Both accept the same options:

mode What reads each page Use it for
text The PDF's own text layer, no AI Digital PDFs at the lowest price
auto (default) The text layer; the AI only for pages with fewer than 30 characters in it (scans) Mixed or unknown files
ai The AI on every selected page Tables, multi-column layouts, forms, clean Markdown

Whatever the mode, the response has the same shape: page_count, pages_extracted, text_pages and ai_pages, the document metadata (title, author, subject, creator, producer, ISO 8601 dates), the whole document as text and markdown (pages separated by ---), and a pages list with each page's number, method and text, plus markdown for pages read by the AI.

Credits: 1 per started 20 pages taken from the text layer, plus 20 per page read by the AI, 1 at least. Failed calls are never billed.

Extract text from a digital PDF with the PDF to text API

The test document is "Attention Is All You Need", the Transformer paper on arXiv: 15 pages typeset with LaTeX, with four results tables.

Python
import requests

HOST = "pdf-to-text-markdown-tables-scanned-pdf-ocr.p.rapidapi.com"
API = f"https://{HOST}"
HEADERS = {"x-rapidapi-key": "YOUR_API_KEY", "x-rapidapi-host": HOST}

response = requests.post(
    f"{API}/v1/pdf/extract",
    headers=HEADERS,
    json={"url": "https://arxiv.org/pdf/1706.03762"},
    timeout=120,
)
response.raise_for_status()
doc = response.json()

print(doc["page_count"], doc["text_pages"], doc["ai_pages"])
for page in doc["pages"]:
    print(page["page"], page["method"], len(page["text"]))

The real response, with pages cut to page 8 and its text cut after the first rows of Table 2:

JSON
{
  "source": "https://arxiv.org/pdf/1706.03762",
  "page_count": 15,
  "pages_extracted": 15,
  "text_pages": 15,
  "ai_pages": 0,
  "metadata": {
    "creator": "LaTeX with hyperref",
    "producer": "pdfTeX-1.40.25",
    "created": "2024-04-10T21:11:43+00:00",
    "modified": "2024-04-10T21:11:43+00:00"
  },
  "pages": [
    {
      "page": 8,
      "method": "text",
      "text": "Table 2: The Transformer achieves better BLEU scores than previous state-of-the-art models on the\nEnglish-to-German and English-to-French newstest2014 tests at a fraction of the training cost.\nModel\nBLEU Training Cost (FLOPs)\nEN-DE EN-FR EN-DE EN-FR\nByteNet [18] 23.75\nDeep-Att + PosUnk [39] 39.2 1.0 · 1020\nGNMT + RL [38] 24.6 39.92 2.3 · 1019 1.4 · 1020\n…"
    }
  ]
}

Every page had a text layer, so auto mode read all 15 from it: no AI, 7 seconds, 1 credit. For full-text search, that is enough.

Look at the table rows, though. Is 39.2 a BLEU score for EN-DE or EN-FR? The text layer cannot say, because empty cells were never drawn. And 1.0 · 1020 is really 1.0 × 10^20 FLOPs, its exponent flattened into the digits. A parser or a model fed this text will make confident mistakes.

PDF to Markdown: extract tables with AI mode

Same document, page 8 only, with mode: "ai":

Python
response = requests.post(
    f"{API}/v1/pdf/extract",
    headers=HEADERS,
    json={"url": "https://arxiv.org/pdf/1706.03762", "mode": "ai", "pages": "8"},
    timeout=120,
)
page = response.json()["pages"][0]
print(page["markdown"])

The real response, markdown cut after the table:

JSON
{
  "page_count": 15,
  "pages_extracted": 1,
  "text_pages": 0,
  "ai_pages": 1,
  "pages": [
    {
      "page": 8,
      "method": "ai",
      "markdown": "Table 2: The Transformer achieves better BLEU scores than previous state-of-the-art models on the English-to-German and English-to-French newstest2014 tests at a fraction of the training cost.\n\n| Model | BLEU (EN-DE) | BLEU (EN-FR) | Training Cost (FLOPs) (EN-DE) | Training Cost (FLOPs) (EN-FR) |\n| :--- | :--- | :--- | :--- | :--- |\n| ByteNet [18] | 23.75 | | | |\n| Deep-Att + PosUnk [39] | | 39.2 | | 1.0 · 10^20 |\n| GNMT + RL [38] | 24.6 | 39.92 | 2.3 · 10^19 | 1.4 · 10^20 |\n…\n| Transformer (big) | 28.4 | 41.8 | 2.3 · 10^19 | |\n\n**Residual Dropout** We apply dropout [33] to the output of each sub-layer, …"
    }
  ]
}

The two-level header became explicit column names, empty cells are kept, so 39.2 now sits in the EN-FR column, and exponents are back (10^20). Further down the same page, inline math comes back as LaTeX ($P_{drop} = 0.1$) and paragraph labels as bold text. The page's text field holds the same content without Markdown syntax, table cells separated by tabs, for code that wants plain text.

That page cost 20 credits and 11 seconds. Digital pages are read at medium resolution together with the PDF's native text, which keeps characters exact while the model rebuilds the structure. Figures become one line, [Figure: <the labels printed in it>], never ASCII art.

The practical rule: index the whole document in auto or text mode for 1 credit, and send only the table pages you need to parse through ai.

Scanned PDF OCR in auto mode

Now a scan. The OCRmyPDF project ships test files; multipage.pdf holds six image-only pages. Pages 1 and 5 are scans of two public-domain novels: a book page with an illustration, and a two-column page.

Python
response = requests.post(
    f"{API}/v1/pdf/extract",
    headers=HEADERS,
    json={
        "url": "https://raw.githubusercontent.com/ocrmypdf/OCRmyPDF/main/tests/resources/multipage.pdf",
        "pages": "1,5",
    },
    timeout=120,
)
scan = response.json()

The real response, texts cut:

JSON
{
  "source": "https://raw.githubusercontent.com/ocrmypdf/OCRmyPDF/main/tests/resources/multipage.pdf",
  "page_count": 6,
  "pages_extracted": 2,
  "text_pages": 0,
  "ai_pages": 2,
  "pages": [
    {
      "page": 1,
      "method": "ai",
      "markdown": "Chapter III.\n\n[Figure: MISS WATSON'S LECTURE.]\n\nWELL, I got a good going-over in the morning, from old Miss Watson, on account of my clothes; …"
    },
    {
      "page": 5,
      "method": "ai",
      "markdown": "with a plain face, on the throne of England; there were a king with a large jaw and a queen with a fair face, on the throne of France. …\n\nIt was the year of Our Lord one thousand seven hundred and seventy-five. Spiritual revelations were conceded to England at that favoured period, as at this. …"
    }
  ]
}

No mode was given, so auto applied: neither page had a text layer, both went to the AI, at high resolution because they are scans. Three details matter for downstream use:

  • Captions stay, drawings go. The engraving becomes one line with its caption, [Figure: MISS WATSON'S LECTURE.], and the ornate "Chapter III" lettering is read as plain text.
  • Columns are read in order. Page 5 comes back as the left column, then the right one, not as interleaved lines.
  • Line-end hyphens are rejoined. The scan prints "reve-" at the end of a line and "lations" on the next; the output says "revelations".

Two pages, 40 credits, 6.5 seconds. Longer scans are read in parallel batches of up to 5 pages.

One caveat, by design: auto trusts any text layer of 30 characters or more. A scan that a copier already ran through a weak OCR engine has such a layer, and auto will return its errors. If a "digital" page comes back as nonsense, re-run those pages with mode: "ai".

Upload, page ranges and passwords

Files on disk go to the upload endpoint as multipart/form-data, field file, up to 30 MB (50 MB by URL). The options are form fields:

Python
with open("contract.pdf", "rb") as f:
    response = requests.post(
        f"{API}/v1/pdf/extract/upload",
        headers=HEADERS,
        files={"file": ("contract.pdf", f, "application/pdf")},
        data={"mode": "auto", "pages": "1-5,8", "password": "s3cret"},
        timeout=120,
    )

pages takes ranges and single pages ("1-5,8,10-12"). A call reads up to 500 pages, of which up to 100 by the AI; split longer scans into ranges. The password is used in memory and never logged. Errors share one shape:

JSON
{ "error": { "status": 400, "code": "pdf_encrypted", "message": "The PDF is password-protected: send its password." } }
Status Codes What to do
400 invalid_pages, site_unreachable, file_too_large, unsupported_file, pdf_encrypted, too_many_pages… Fix the input; retrying changes nothing
429 daily_limit_reached Stop until 00:00 UTC
503 ai_error, capacity_exhausted Temporary: retry

None of them is billed.

Chunking PDF text for RAG, with page numbers

Retrieval works better when every chunk knows where it came from. The pages list gives you that for free. The function below keeps one or more chunks per page and splits Markdown before headings, then on blank lines. A Markdown table has no blank line inside it, so a table is never cut in half:

Python
import re


def chunks(doc: dict, max_chars: int = 2000) -> list[dict]:
    out = []
    for page in doc["pages"]:
        body = page.get("markdown") or page["text"]
        for section in re.split(r"\n(?=#{1,4} )", body):  # before each heading
            buf = ""
            for block in section.split("\n\n"):  # paragraphs, lists, whole tables
                if buf and len(buf) + len(block) > max_chars:
                    out.append(
                        {"page": page["page"], "method": page["method"], "text": buf}
                    )
                    buf = ""
                buf = f"{buf}\n\n{block}" if buf else block
            if buf.strip():
                out.append(
                    {"page": page["page"], "method": page["method"], "text": buf}
                )
    return out

Store page with each vector and answers can cite "page 8". Keep method too: when retrieval is poor on a document, text-layer chunks of multi-column pages are the first suspects, and ai mode on those pages the fix.

A batch pipeline with retries and cost control

The script below extracts a folder, writes one JSON file per PDF, logs the credits used and stops cleanly on the daily limit. Credits can be computed from the response, so you can track spend without reading headers:

Python
import json
import math
import pathlib
import time

import requests

HOST = "pdf-to-text-markdown-tables-scanned-pdf-ocr.p.rapidapi.com"
API = f"https://{HOST}"
HEADERS = {"x-rapidapi-key": "YOUR_API_KEY", "x-rapidapi-host": HOST}


def credits(doc: dict) -> int:
    return max(1, math.ceil(doc["text_pages"] / 20) + 20 * doc["ai_pages"])


def extract(path: pathlib.Path, mode: str = "auto", attempts: int = 3) -> dict:
    for attempt in range(attempts):
        with path.open("rb") as f:
            r = requests.post(
                f"{API}/v1/pdf/extract/upload",
                headers=HEADERS,
                files={"file": (path.name, f, "application/pdf")},
                data={"mode": mode},
                timeout=180,
            )
        if r.status_code == 503:  # AI hiccup: not billed, try again
            time.sleep(5 * 2**attempt)
            continue
        if r.status_code == 429:
            raise SystemExit("Daily limit reached; resume tomorrow.")
        return r.json()  # the document, or {"error": {...}} for a 400
    return {"error": {"code": "gave_up"}}


out_dir = pathlib.Path("extracted")
out_dir.mkdir(exist_ok=True)
total = 0
for path in sorted(pathlib.Path("inbox").glob("*.pdf")):
    doc = extract(path)
    if "error" in doc:
        print(path.name, "ERROR", doc["error"]["code"])
        continue
    total += credits(doc)
    (out_dir / f"{path.stem}.json").write_text(json.dumps(doc), encoding="utf-8")
    print(path.name, doc["page_count"], "pages,", doc["ai_pages"], "by AI")
print("credits used:", total)

In production:

  • Watch ai_pages. It tells you which documents were scans. If a digital batch suddenly reports AI pages, the sender changed their export.
  • Trim before you pay. Skip appendices and annexes with pages.
  • Deduplicate by hash. The same PDF often arrives twice; hash the bytes before calling.
  • Timeouts. A text-layer document takes seconds, an AI batch of 5 pages about 10; a 180-second client timeout leaves room.

What it costs

Plan Price per month Credits In practice
BASIC Free 20 per day Up to 20 pages per call, 1 of them by the AI
PRO $4.99 16,000 16,000 digital PDFs of up to 20 pages, or 800 AI pages (about $0.006 each)
ULTRA $14.99 48,000 2,400 AI pages
MEGA $49.99 160,000 8,000 AI pages

Beyond the quota, paid plans continue at $0.0035 per credit. Plans and parameters: the product page and the API reference. For invoices, where you want accounting fields rather than text, see the invoice OCR walkthrough; for CVs, the resume parser article.

Run it without code on Apify

The same engine runs as an Apify Actor, PDF to Text Extractor - Scanned PDF OCR. Paste PDF links, or the dataset of an Actor that collected them, and get one row per PDF. It charges $0.0002 per text-layer page and $0.0045 per page read by the AI; failed PDFs are free. For comparison, a popular PDF extractor on the Apify Store charges $0.005 per PDF plus $0.015 per OCR page. Password-protected PDFs need the API.

What the PDF to text API does not do

  • No coordinates. You get text and Markdown per page, not bounding boxes, fonts or positions.
  • No images out. Figures become a line of labels; embedded images are not returned.
  • PDF only. Convert Word and PowerPoint files to PDF first. For photos, use the Image to Text OCR API.
  • No second opinion on text layers. auto trusts an existing text layer, good or bad. Use ai for pages you doubt.
  • No summaries or answers. It extracts; it does not summarise or answer questions.
  • Limits per call. 50 MB by URL, 30 MB by upload, 500 pages, 100 of them read by the AI (20 and 1 on the free plan).

Frequently asked questions

How do I convert a PDF to text in Python?

For digital PDFs, pypdf (page.extract_text()) works locally, with the reading-order and table caveats above. When files may be scanned or tables matter, post the PDF to a PDF to text API with requests and read pages[].text or pages[].markdown.

How do I extract tables from a PDF?

Text-layer extraction loses the cell grid, so values drift between columns. Read the table pages with mode: "ai": they come back as Markdown tables, headers and empty cells kept.

Can it OCR a scanned PDF?

Yes. In the default auto mode, any page whose text layer holds fewer than 30 characters is read by AI OCR at high resolution, handwriting included. Digital pages in the same file keep their exact text layer.

Is PDF to Markdown better than plain text for RAG?

Usually. Markdown keeps headings, lists and tables, which chunkers use to cut at sensible boundaries, and tables stay readable to the model. Plain text is enough for keyword search and costs far less on digital PDFs.

Are my PDFs stored?

No. Files are downloaded, read and discarded; neither the file nor its text is stored by the API, and passwords are never logged. The AI provider may keep requests temporarily for abuse monitoring.

Get started

PDF to Text API

PDF to text page by page with metadata; AI OCR for scanned pages and clean Markdown with tables.

  • PDF
  • OCR
  • RAG
  • Python
  • Document Processing