# PDF to Markdown, Text & Tables for LLMs (`goldish_boss/pdf-to-markdown`) Actor

Convert PDF URLs into LLM-ready Markdown with every table as structured cells (Markdown/CSV/JSON, with page numbers) and page-aware RAG chunks. Text-layer PDFs, no OCR.

- **URL**: https://apify.com/goldish_boss/pdf-to-markdown.md
- **Developed by:** [frank zhang](https://apify.com/goldish_boss) (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 $2.00 / 1,000 pdf processeds

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/running/actors-in-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 & Tables for LLMs

Turn any public PDF URL into LLM-ready Markdown **with every table returned as structured cells** (Markdown, CSV or JSON, one entry per table with its page number) and optional **page-aware RAG chunks** (`pageStart`/`pageEnd` on every chunk). Built for RAG pipelines, AI agents and document-processing workflows that need the numbers in a table, not a flattened blob of text.

**Why this Actor**

- **Tables as data, not text.** Ruled grids and booktabs-style (LaTeX/arXiv) tables come out as rows and columns you can load straight into a dataframe or a prompt. On a hand-checked test set of 10 public PDFs (68 tables), precision is 0.92 and recall 0.82.
- **Chunks that know their pages.** Each RAG chunk carries its page span, so answers can cite "page 12" back to the source.
- **Clean text around the tables.** Two-column reading order, headings, and running headers and footers removed.

It uses the PDF's text layer only: no OCR, no AI calls, no proxies.

### What does it do?

- Downloads each PDF (http/https, up to 50 MB by default) and extracts the text layer.
- Keeps **reading order on two-column pages** (papers, government publications) and turns large or bold lines into `#` / `##` / `###` **headings**.
- Detects **ruled tables and booktabs-style tables** (common in arXiv/LaTeX papers) and writes them inline as Markdown tables, plus a structured `tables` array in your chosen format.
- Strips **repeated running headers and footers** (page numbers, document titles, "VerDate … Jkt" print lines) by default; set `removeHeadersFooters` to `false` to keep them.
- Removes rotated margin stamps (for example, the arXiv sidebar), repairs end-of-line hyphenation and fixes duplicated "faux-bold" characters.
- Optional **chunking**: produces one dataset item per ~N-character chunk, with overlap, `pageStart`/`pageEnd` and chunk index, ready to embed.
- **Never fails the whole run on a bad file.** A broken URL, non-PDF, oversized, encrypted or scanned PDF becomes an error item with an `errorCode`.
- **Respects your spending limit.** If the remaining budget cannot pay for a whole PDF, the Actor keeps only the leading pages it can pay for and marks the item `truncated: true`, `truncatedReason: "budget"`. You are never given output you were not charged for, and never charged past your limit.

### Input

| Field | Type | Default | Description |
|---|---|---|---|
| `pdfUrls` | array (required) | – | PDF URLs, e.g. `[{"url": "https://arxiv.org/pdf/2310.06825"}]` |
| `outputFormat` | `markdown` | `text` | `json` | `markdown` | `json` returns one entry per page (`markdown`, `text`, `tables`) |
| `extractTables` | boolean | `true` | Detect tables (each one billed as `table-extracted`) |
| `tableFormat` | `markdown` | `csv` | `json` | `markdown` | Format of `tables[].data` |
| `pageRange` | string | all | e.g. `"1-5,9"` or `"10-"` |
| `maxPagesPerPdf` | integer | `200` | Hard cap on pages per PDF |
| `chunking` | object | off | `{"enabled": true, "chunkSizeChars": 2000, "overlapChars": 200}` |
| `includeMetadata` | boolean | `true` | Title, author, producer, dates, page count |
| `maxFileSizeMb` | integer | `50` | Larger files are rejected (`FILE_TOO_LARGE`) |
| `removeHeadersFooters` | boolean | `true` | Drop lines that repeat in the top/bottom margin on many pages (running headers, footers, page numbers) |

Example input:

```json
{
  "pdfUrls": [{ "url": "https://arxiv.org/pdf/2310.06825" }],
  "outputFormat": "markdown",
  "extractTables": true,
  "tableFormat": "csv",
  "chunking": { "enabled": false }
}
```

### Output

One dataset item per PDF (or one per chunk when chunking is on). This is a real, shortened result for the Mistral 7B paper (arXiv 2310.06825, CC BY 4.0):

```json
{
  "url": "https://arxiv.org/pdf/2310.06825",
  "status": "success",
  "fileName": "2310.06825",
  "pageCount": 9,
  "pagesProcessed": 9,
  "truncated": false,
  "failedPages": [],
  "tableCount": 5,
  "charCount": 25921,
  "markdown": "# Mistral 7B\n\nAlbert Q. Jiang, Alexandre Sablayrolles, ...\n\n### Abstract\n\nWe introduce Mistral 7B, a 7–billion-parameter language model ...\n\n| Parameter | Value |\n| --- | --- |\n| dim | 4096 |\n| n_layers | 32 | ...",
  "tables": [
    { "tableIndex": 1, "page": 2, "rows": 10, "columns": 2, "format": "markdown", "data": "| Parameter | Value |\n| --- | --- |\n| dim | 4096 | ..." }
  ],
  "metadata": { "title": null, "producer": "pdfTeX-1.40.25", "creationDate": "D:20231011004817Z", "pageCount": 9 },
  "processingMs": 1047,
  "chargedEvents": { "pdf-processed": 1, "table-extracted": 5 }
}
```

Error item (you are told why, and the run continues):

```json
{ "url": "https://example.com/scan.pdf", "status": "error", "errorCode": "NO_TEXT_LAYER",
  "errorMessage": "Only 0 text characters found in 3 page(s). The PDF looks scanned or image-only; OCR is not supported by this Actor.",
  "chargedEvents": { "invalid-input": 1 } }
```

Error codes and billing:

| Charged as `invalid-input` ($0.0005), a problem with the input | Not charged, not your fault |
|---|---|
| `INVALID_URL`, `DOWNLOAD_FAILED` (HTTP 403, 404 or other 4xx), `NOT_A_PDF`, `FILE_TOO_LARGE`, `ENCRYPTED_PDF`, `CORRUPT_PDF`, `EMPTY_PDF`, `INVALID_PAGE_RANGE`, `NO_TEXT_LAYER` | `SERVER_ERROR` (HTTP 5xx, 408, 425, 429 after 3 attempts), `TIMEOUT`, `NETWORK_ERROR` (after 3 attempts), `INTERNAL_ERROR` (a bug on our side) |

Each item also has `truncatedReason` (`null`, `maxPagesPerPdf` or `budget`) and `headerFooterLinesRemoved`.

A run summary is saved to the key-value store as `OUTPUT_SUMMARY`.

### Pricing (pay per event)

You pay only for results. There is no monthly fee.

| Event | Price | When |
|---|---|---|
| PDF processed | **$0.002** | Each PDF converted successfully. Covers up to 20 pages. |
| Extra page | $0.0002 | Each processed page above 20 in one PDF |
| Table extracted | $0.001 | Each detected table (turn off `extractTables` to skip) |
| Invalid input | $0.0005 | Only for input problems: bad URL, HTTP 4xx (403/404), not a PDF, too large, encrypted, corrupt, empty, bad page range, or scanned (no text layer). Server errors (5xx), timeouts, network failures and our own errors are **free**. |

Examples: a 9-page paper with 5 tables costs **$0.007**. A 59-page IRS publication with 11 tables costs **$0.0208**. 1,000 ten-page PDFs without tables cost **$2**. Chunks and dataset items are free. There is no start fee. The Actor stops when it reaches your **maximum cost per run**.

### Limits

- **No OCR.** Scanned or image-only PDFs return `NO_TEXT_LAYER`.
- Tables must be drawn with lines (full grid or booktabs-style top/mid/bottom rules). Whitespace-only tables are kept as text. Multi-line cells in partly ruled grids may be merged. Sparse boxes (chart panels, cover-page frames) are filtered out, but some chart grids can still appear as tables. Tables whose row labels sit outside the ruled area can lose that label column.
- Heading detection uses font size and boldness, so very unusual layouts may produce extra or missing headings. Header/footer removal needs the line to repeat on at least 3 pages (and 30% of pages), so short documents keep theirs.
- Two-column layout is supported. Three or more columns, or rotated pages, may interleave.
- Public URLs only (no login, no cookies). Defaults are 50 MB and 200 pages per PDF. Memory is 512 MB–1 GB, and a 1,500-page file can take several minutes.
- Pure-Python, permissively licensed stack: pdfplumber and pdfminer.six (MIT), httpx (BSD) and the Apify SDK (Apache-2.0). No AGPL components.

### FAQ

**Why Markdown?** LLMs understand headings and tables in Markdown better than raw PDF text, and it uses fewer tokens than HTML.

**Can I feed the output straight into a vector DB?** Yes. Turn on `chunking` and each item has `content`, `chunkIndex`, `pageStart` and `pageEnd`.

**My PDF is behind a login.** Not supported. Upload it somewhere public (for example, an Apify key-value store record with a public URL) and pass that URL.

# Actor input Schema

## `pdfUrls` (type: `array`):

Direct links to PDF files (http or https). One result is produced per PDF (or per chunk if chunking is on).

## `outputFormat` (type: `string`):

markdown: headings, paragraphs and tables in Markdown (best for LLMs). text: plain text, tables as CSV. json: one entry per page with markdown, text and tables.

## `extractTables` (type: `boolean`):

Detect ruled and booktabs-style tables and return them as structured data. Each detected table is billed as a 'table-extracted' event.

## `tableFormat` (type: `string`):

Format of the 'data' field of each item in 'tables'. Tables are always shown inline as Markdown in the 'markdown' output.

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

Pages to process, 1-based. Examples: "1-5", "1-5,9", "10-". Leave empty for all pages.

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

Hard cap on pages processed per PDF (after pageRange). Pages above 20 are billed as 'extra-page' events.

## `chunking` (type: `object`):

Split each document into overlapping chunks, one dataset item per chunk. Example: {"enabled": true, "chunkSizeChars": 2000, "overlapChars": 200}. Chunks are free; you pay per PDF.

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

Drop text in the top/bottom page margins that repeats on many pages (page numbers, running titles, printer's slugs). Needs at least 3 processed pages.

## `includeMetadata` (type: `boolean`):

Add title, author, producer, dates and page count from the PDF info dictionary.

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

Larger files are rejected with FILE_TOO_LARGE (billed as 'invalid-input').

## Actor input object example

```json
{
  "pdfUrls": [
    {
      "url": "https://arxiv.org/pdf/2310.06825"
    }
  ],
  "outputFormat": "markdown",
  "extractTables": true,
  "tableFormat": "markdown",
  "maxPagesPerPdf": 200,
  "chunking": {
    "enabled": false,
    "chunkSizeChars": 2000,
    "overlapChars": 200
  },
  "removeHeadersFooters": true,
  "includeMetadata": true,
  "maxFileSizeMb": 50
}
```

# Actor output Schema

## `overview` (type: `string`):

Markdown/text, tables and chunks per PDF in the default dataset (overview table view).

## `summary` (type: `string`):

OUTPUT_SUMMARY record: PDFs succeeded/failed, pages, tables and total charged.

# 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 = {
    "pdfUrls": [
        {
            "url": "https://arxiv.org/pdf/2310.06825"
        }
    ],
    "chunking": {
        "enabled": false,
        "chunkSizeChars": 2000,
        "overlapChars": 200
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("goldish_boss/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 = {
    "pdfUrls": [{ "url": "https://arxiv.org/pdf/2310.06825" }],
    "chunking": {
        "enabled": False,
        "chunkSizeChars": 2000,
        "overlapChars": 200,
    },
}

# Run the Actor and wait for it to finish
run = client.actor("goldish_boss/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 '{
  "pdfUrls": [
    {
      "url": "https://arxiv.org/pdf/2310.06825"
    }
  ],
  "chunking": {
    "enabled": false,
    "chunkSizeChars": 2000,
    "overlapChars": 200
  }
}' |
apify call goldish_boss/pdf-to-markdown --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,goldish_boss/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/HUeBSuQmSJOjyV3QO/builds/bXghMA0oCVMHcgW8f/openapi.json
