# PDF to Markdown & Text Extractor (Tables, RAG Chunks) (`omitsu_dev/pdf-to-markdown`) Actor

Convert PDFs from URLs into clean Markdown and plain text with headings, lists and tables, plus optional RAG-ready chunks with page numbers. Flat price per PDF. No OCR.

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

## Pricing

from $3.00 / 1,000 pdf extracted

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 & Text Extractor

Turn PDFs into clean **Markdown** and **plain text**, with headings, lists and tables kept, plus optional **RAG-ready chunks** that carry page numbers and heading paths.

Give it a list of PDF URLs. You get one dataset item per PDF.

- **Markdown** with `#` headings, bullet and numbered lists, and Markdown tables
- **Plain text** in reading order, including simple two-column layouts
- **Tables** as rows (arrays) and as Markdown
- **Chunks** for embeddings, each with `pageStart`, `pageEnd` and `headings`
- **Metadata**: title, author, dates, page count, file size
- Running headers, footers and page numbers removed by default
- Password-protected PDFs supported with `password`
- **Flat price per PDF.** Failed downloads and PDFs without text are not charged

### What it does not do

Read this before you run it on a large batch.

- **No OCR.** Scanned or image-only PDFs come back with `status: "no_text"` and are free.
- **Tables need visible lines.** Tables drawn with ruling lines are detected. Tables laid out only with spacing come back as normal text.
- **Headings are inferred from font size and weight.** This works for most reports, papers and manuals. Documents that use one font size throughout get few or no headings.
- **Layout support is simple.** One and two columns are handled. Three or more columns, sidebars and text wrapped around figures can come out in the wrong order.
- **Images, formulas and footnote links are not extracted.**
- **URLs must be public** and return the PDF itself. Pages that only link to a PDF are not followed.

### Input

| Field | Type | Default | Description |
|---|---|---|---|
| `urls` | array of strings | required | Direct links to PDF files |
| `includeMarkdown` | boolean | `true` | Return Markdown |
| `includeText` | boolean | `true` | Return plain text |
| `includeTables` | boolean | `true` | Detect ruled tables |
| `includeChunks` | boolean | `false` | Return chunks for RAG |
| `chunkSize` | integer | `1500` | Target chunk size in characters |
| `chunkOverlap` | integer | `200` | Overlap between chunks in characters |
| `includePages` | boolean | `false` | Also return text and Markdown per page |
| `pageRange` | string | all | For example `1-5`, `3`, `10-` |
| `maxPagesPerPdf` | integer | `300` | Stop after this many pages |
| `removeHeadersFooters` | boolean | `true` | Drop repeated margin lines and page numbers |
| `password` | string | none | For encrypted PDFs |
| `maxPdfSizeMb` | integer | `50` | Skip larger files |
| `timeoutPerPdfSecs` | integer | `120` | Limit per PDF |
| `maxConcurrency` | integer | `3` | PDFs processed in parallel |

```json
{
  "urls": ["https://example.com/annual-report.pdf"],
  "includeChunks": true,
  "chunkSize": 1500
}
```

### Output

One item per PDF. Long fields are shortened here.

```json
{
  "url": "https://example.com/annual-report.pdf",
  "status": "ok",
  "error": null,
  "warning": null,
  "fileName": "annual-report.pdf",
  "fileSizeBytes": 482113,
  "pageCount": 12,
  "pagesProcessed": 12,
  "metadata": { "title": "Annual Report", "author": "Example Corp", "creationDate": "2025-03-01T09:00:00" },
  "markdown": "# Annual Report\n\n## 1. Overview\n\nRevenue grew ...\n\n| Segment | 2024 | 2025 |\n| --- | --- | --- |\n| Cloud | 120 | 150 |",
  "text": "Annual Report\n\n1. Overview\n\nRevenue grew ...",
  "tables": [
    { "index": 0, "pageNumber": 3, "rows": [["Segment", "2024", "2025"], ["Cloud", "120", "150"]], "markdown": "| Segment | 2024 | 2025 |\n| --- | --- | --- |\n| Cloud | 120 | 150 |" }
  ],
  "chunks": [
    { "index": 0, "text": "# Annual Report\n\n## 1. Overview\n\nRevenue grew ...", "charCount": 1432, "pageStart": 1, "pageEnd": 2, "headings": ["Annual Report", "1. Overview"] }
  ],
  "stats": { "charCount": 28411, "wordCount": 4630, "tableCount": 4, "headingCount": 17, "removedHeaderFooterLines": 22, "processingMs": 2140 }
}
```

`status` is one of:

- `ok`: text was extracted. This is the only status that is charged.
- `no_text`: the PDF opened, but it has almost no embedded text (usually a scan).
- `failed`: the download or the PDF could not be processed. `error` says why.

If a result is too large for one dataset item, the largest optional fields are left out and `warning` says which. Use `pageRange` to split very long documents.

### Pricing

Pay per event.

| Event | Price | When |
|---|---|---|
| `pdf-extracted` | $0.003 | Once per PDF with `status: "ok"`. Covers the first 25 pages |
| `extra-pages` | $0.002 | Once per additional 25 pages processed, rounded up |
| `apify-actor-start` | $0.00005 | Once per run |

Examples: a 10-page PDF costs $0.003. An 80-page PDF costs $0.003 + 3 × $0.002 = $0.009. Platform usage is included.

Failed downloads, PDFs that are not PDFs, and `no_text` results are not charged. Markdown, tables and chunks add no fee. The Pricing tab always shows the current prices.

### Automate it: a PDF inbox with GitHub Actions

Keep a list of PDF links in your repository. Every time the list changes, and once every night, a GitHub Action converts the new ones and commits clean Markdown and chunk files to a `knowledge/` folder. No server needed.

Measured on three NIST reports (139 pages in total): 9 to 22 seconds per run, list price $0.017. A dead link in the same list failed and cost nothing.

1. Add your Apify API token to your repository as the secret `APIFY_TOKEN`.
2. Add the three files below to the root of the repository.
3. Put PDF links in `pdfs.txt` and push.

**`pdfs.txt`**

```
## One PDF URL per line. Lines starting with # are ignored.
https://nvlpubs.nist.gov/nistpubs/CSWP/NIST.CSWP.29.pdf
```

**`.github/workflows/pdf-inbox.yml`**

```yaml
name: pdf-inbox

on:
  push:
    branches: [main]
    paths: ["pdfs.txt", "convert.py", ".github/workflows/pdf-inbox.yml"]
  schedule:
    - cron: "41 2 * * *"

permissions:
  contents: write

jobs:
  convert:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.13"
      - name: Convert new PDFs
        env:
          APIFY_TOKEN: ${{ secrets.APIFY_TOKEN }}
        run: python convert.py | tee last_run.log
      - name: Commit
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git add -A
          git diff --cached --quiet || (git commit -m "pdf-inbox: convert new PDFs" && git pull --rebase origin main && git push origin HEAD:main)
```

**`convert.py`** (standard library only)

```python
"""PDF inbox: convert every new PDF URL in pdfs.txt to Markdown with an Apify Actor.

Standard library only. Needs the APIFY_TOKEN environment variable.
Writes knowledge/<name>.md, knowledge/<name>.chunks.json and state.json, and prints a summary.
"""
from __future__ import annotations

import datetime as dt
import json
import os
import re
import sys
import time
import urllib.error
import urllib.request
from pathlib import Path

ACTOR = "omitsu_dev~pdf-to-markdown"
API = "https://api.apify.com/v2"
HERE = Path(__file__).parent
OUT = HERE / "knowledge"
STATE = HERE / "state.json"
PRICE_PDF, PRICE_EXTRA, PAGES_INCLUDED, START_FEE = 0.003, 0.002, 25, 0.00005


def api(method: str, path: str, body: dict | None = None):
    req = urllib.request.Request(API + path, data=json.dumps(body).encode() if body is not None else None, method=method)
    req.add_header("Authorization", "Bearer " + os.environ["APIFY_TOKEN"].strip())
    req.add_header("Content-Type", "application/json")
    for attempt in range(5):
        try:
            with urllib.request.urlopen(req, timeout=90) as resp:
                return json.loads(resp.read().decode())
        except urllib.error.HTTPError as exc:
            if exc.code < 500 or method == "POST":
                raise
        except OSError:
            if method == "POST":
                raise
        time.sleep(3)
    raise RuntimeError("Apify API did not answer")


def slug(url: str) -> str:
    name = url.rstrip("/").rsplit("/", 1)[-1]
    name = re.sub(r"\.pdf$", "", name, flags=re.I)
    return re.sub(r"[^A-Za-z0-9._-]+", "-", name).strip("-") or "document"


def list_price(pages: int) -> float:
    extra = max(0, -(-(pages - PAGES_INCLUDED) // 25))
    return PRICE_PDF + extra * PRICE_EXTRA


def main() -> None:
    urls = [l.strip() for l in (HERE / "pdfs.txt").read_text().splitlines() if l.strip() and not l.startswith("#")]
    state = json.loads(STATE.read_text()) if STATE.exists() else {}
    todo = [u for u in urls if u not in state or "--force" in sys.argv]
    summary: dict = {"ran_at": dt.datetime.now(dt.timezone.utc).isoformat(timespec="seconds"), "in_list": len(urls), "new": len(todo), "items": []}
    if not todo:
        print("Nothing new. All", len(urls), "PDFs are already converted.")
        (HERE / "last_run.json").write_text(json.dumps(summary, indent=2) + "\n")
        return

    started = time.time()
    run = api("POST", f"/acts/{ACTOR}/runs", {"urls": todo, "includeChunks": True, "includeText": False})["data"]
    while run["status"] in ("READY", "RUNNING"):
        run = api("GET", f"/actor-runs/{run['id']}?waitForFinish=30")["data"]
    items = api("GET", f"/datasets/{run['defaultDatasetId']}/items?clean=1")

    OUT.mkdir(exist_ok=True)
    total_price = START_FEE
    for it in items:
        url, name = it["url"], slug(it["url"])
        row = {"url": url, "status": it["status"], "pages": it.get("pagesProcessed"), "error": it.get("error")}
        if it["status"] == "ok":
            meta = it.get("metadata") or {}
            front = f"---\nsource: {url}\ntitle: {json.dumps(meta.get('title') or name)}\npages: {it['pagesProcessed']}\nconverted: {summary['ran_at']}\n---\n\n"
            (OUT / f"{name}.md").write_text(front + it["markdown"] + "\n", encoding="utf-8")
            (OUT / f"{name}.chunks.json").write_text(json.dumps(it.get("chunks") or [], ensure_ascii=False, indent=1), encoding="utf-8")
            row.update(file=f"knowledge/{name}.md", chars=len(it["markdown"]), chunks=len(it.get("chunks") or []),
                       tables=(it.get("stats") or {}).get("tableCount"), headings=(it.get("stats") or {}).get("headingCount"),
                       extract_ms=(it.get("stats") or {}).get("processingMs"), list_price_usd=round(list_price(it["pagesProcessed"]), 4))
            total_price += row["list_price_usd"]
        else:
            row["list_price_usd"] = 0.0
        state[url] = {"status": it["status"], "converted": summary["ran_at"]}
        summary["items"].append(row)

    summary.update(run_status=run["status"], wall_seconds=round(time.time() - started, 1),
                   run_seconds=(run.get("stats") or {}).get("runTimeSecs"), list_price_total_usd=round(total_price, 5))
    STATE.write_text(json.dumps(state, indent=2) + "\n")
    (HERE / "last_run.json").write_text(json.dumps(summary, indent=2) + "\n")
    for r in summary["items"]:
        print(f"{r['status']:8} {str(r.get('pages') or '-'):>4} pages  ${r['list_price_usd']:.4f}  {r['url']}")
    print(f"Done in {summary['wall_seconds']} s. List price for this run: ${summary['list_price_total_usd']}")


if __name__ == "__main__":
    main()
```

### Tips

- For RAG, turn on `includeChunks` and store `pageStart` and `headings` with each embedding so answers can cite the page.
- For a quick check of a long document, set `pageRange` to `1-10`.
- If a run stops on a very large PDF, give the run more memory or lower `maxPagesPerPdf`.

### Privacy

PDFs are downloaded into the run's memory, processed, and discarded when the run ends. Only the output you see in the dataset is stored, in your own Apify account. Do not submit confidential documents through public URLs.

### About this Actor

This Actor was written and is maintained by an AI agent (Anthropic's Claude) running under the account owner's supervision. Extraction uses the open-source libraries pdfplumber and pdfminer.six. If something comes out wrong, open an issue on the Issues tab with the PDF URL, and it will be looked at.

# Actor input Schema

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

Direct links to PDF files. Each URL must be publicly reachable and return the PDF itself.

## `includeMarkdown` (type: `boolean`):

Return the document as Markdown with headings, lists and tables.

## `includeText` (type: `boolean`):

Return the document as plain text in reading order.

## `includeTables` (type: `boolean`):

Detect tables drawn with ruling lines and return them as rows and as Markdown tables. Tables without visible lines are returned as normal text.

## `includeChunks` (type: `boolean`):

Split the Markdown into chunks for embeddings. Each chunk carries its page span and heading path.

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

Target size of each chunk in characters. Tables are kept whole when they fit in twice this size.

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

Trailing paragraphs repeated at the start of the next chunk, up to this many characters.

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

Also return text and Markdown for each page separately.

## `pageRange` (type: `string`):

Pages to process, for example 1-5, 3, or 10-. Leave empty for all pages.

## `maxPagesPerPdf` (type: `integer`):

Stop after this many pages of each PDF. Limits cost and run time for very long documents.

## `removeHeadersFooters` (type: `boolean`):

Drop lines that repeat in the top or bottom margin on at least half of the pages, and bare page numbers.

## `password` (type: `string`):

Password for encrypted PDFs. Applied to every PDF in the run.

## `maxPdfSizeMb` (type: `integer`):

PDFs larger than this are skipped with an error.

## `timeoutPerPdfSecs` (type: `integer`):

Maximum time for downloading and for extracting one PDF.

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

How many PDFs to process in parallel.

## Actor input object example

```json
{
  "urls": [
    "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
  ],
  "includeMarkdown": true,
  "includeText": true,
  "includeTables": true,
  "includeChunks": false,
  "chunkSize": 1500,
  "chunkOverlap": 200,
  "includePages": false,
  "maxPagesPerPdf": 300,
  "removeHeadersFooters": true,
  "maxPdfSizeMb": 50,
  "timeoutPerPdfSecs": 120,
  "maxConcurrency": 3
}
```

# Actor output Schema

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

One dataset item per PDF with Markdown, text, tables and 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://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("omitsu_dev/pdf-to-markdown").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://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"] }

# Run the Actor and wait for it to finish
run = client.actor("omitsu_dev/pdf-to-markdown").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://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
  ]
}' |
apify call omitsu_dev/pdf-to-markdown --silent --output-dataset

```

## MCP server setup

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

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/qsPQJkiDLVbVJRn3M/builds/coZSsDRnTBSnqmexd/openapi.json
