# PDF to Markdown - Text, Tables, CJK-safe (`teal_blacksmith/pdf-to-markdown`) Actor

PDF URLs to RAG-ready Markdown, text or chunks with page refs. Headings, lists, tables, header/footer removal, Korean/Japanese/Chinese safe. $0.003 per PDF up to 50 pages, only when it works. No OCR: scans are flagged, free.

- **URL**: https://apify.com/teal_blacksmith/pdf-to-markdown.md
- **Developed by:** [도영 김](https://apify.com/teal_blacksmith) (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 converted (up to 50 pages)s

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, CJK-safe

Turn PDF URLs into **RAG-ready Markdown**, plain text, or **token-sized chunks with page references**. The Actor reads the text layer of each PDF with Mozilla's PDF.js, puts it back into reading order (two-column pages included), and rebuilds headings, lists, paragraphs and simple tables. Korean, Japanese and Chinese PDFs are decoded with PDF.js's bundled CMaps, and every row carries a `garbledRatio` so you can see when text did not come out clean.

- **Pay only when it worked.** $0.003 per PDF with status `ok`, covering up to 50 pages. Failed, empty, encrypted and scanned PDFs are saved as rows and not charged.
- **Honest about what it cannot do.** There is **No OCR**. A page without a text layer is reported (`pagesWithoutText`, `scannedLikely`), never guessed. A PDF where no page has text gets status `no_text` and is free.
- **Made for RAG.** `outputMode: "chunks"` splits the Markdown into chunks of about `chunkSize` tokens, each with `pageStart`, `pageEnd` and the `headingPath` it sits under.
- **Plain HTTP.** No browser, no proxy, no third-party conversion service. The PDF is parsed inside the run and is not sent anywhere else.

### Who it is for

- Developers building RAG, search or agents over PDFs, including Korean, Japanese and Chinese government and corporate documents
- Teams that need a quality signal per document (`garbledRatio`, `scannedLikely`, per-page character counts) to route bad files to OCR or a human
- Anyone who wants metadata (title, author, page count, created, producer) next to the text

### Input

```json
{
  "urls": [
    "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
    "https://arxiv.org/pdf/1706.03762"
  ],
  "outputMode": "chunks",
  "chunkSize": 800,
  "pageRange": "1-5",
  "maxPages": 50
}
```

| Field | Type | Default | Notes |
|---|---|---|---|
| `urls` | string\[] | required | 1 to 500 public `http(s)` URLs. Redirects are followed. |
| `outputMode` | string | `markdown` | `markdown`, `text` or `chunks`. Same price for all. |
| `chunkSize` | integer | `800` | 100 to 4000 estimated tokens per chunk. Used only for `chunks`. |
| `pageRange` | string | all | For example `1-5,8,10-`. |
| `maxPages` | integer | `50` | 1 to 1000. See pricing: pages beyond 50 cost extra. |
| `maxFileSizeMb` | integer | `30` | 1 to 100. Larger files get `too_large`. |
| `includePages` | boolean | `false` | Adds `pages[]` with the plain text of each page. |
| `removeHeadersFooters` | boolean | `true` | Drops lines in the top or bottom margin that repeat on at least 40% of the pages (3 or more pages). Bare page numbers in the margin are always dropped. |
| `detectTables` | boolean | `true` | Aligned columns of text become Markdown tables. |
| `pageMarkers` | boolean | `false` | Adds `<!-- page N -->` comments to the Markdown. |
| `timeoutPerPdfSecs` | integer | `120` | 10 to 600. Download and conversion of one PDF. |
| `maxConcurrency` | integer | `2` | 1 to 4 downloads at once. Parsing runs one PDF at a time. |

#### URL rules

Only `http` and `https` URLs on the default ports are fetched. URLs with a user name and password, custom ports, `localhost`, internal host names, or addresses in private, loopback, link-local and cloud-metadata ranges are refused with `INVALID_URL` or `UNSAFE_ADDRESS`. The check runs on every redirect and on the resolved IP address, so a public name that points to a private address is refused as well. The file type is decided by the `%PDF-` signature, not by the extension or the `Content-Type` header.

### Output

One dataset row per input URL, in the order the conversions finish (use `index` for the input order). Example (shortened):

```json
{
  "index": 0,
  "url": "https://example.com/report.pdf",
  "finalUrl": "https://example.com/report.pdf",
  "status": "ok",
  "reason": null,
  "charged": true,
  "extraPageBlocks": 0,
  "title": "Annual Findings",
  "author": "Test Author",
  "createdAt": "2007-02-23T15:56:37.000Z",
  "producer": "OpenOffice.org 2.1",
  "pageCount": 3,
  "pagesProcessed": 3,
  "truncated": false,
  "scannedLikely": false,
  "pagesWithoutText": [],
  "garbledRatio": 0,
  "headingCount": 5,
  "tableCount": 1,
  "listCount": 2,
  "removedHeaderFooterLines": 6,
  "charCount": 438,
  "tokensEstimate": 89,
  "pageStats": [{ "page": 1, "chars": 357, "hasText": true, "columns": 1, "garbledRatio": 0 }],
  "warnings": [],
  "markdown": "# Annual Findings\n\n## Overview\n\nThis report describes ...\n\n| Region | Units | Revenue |\n| --- | --- | --- |\n| North | 120 | 4,500 |",
  "durationMs": 312
}
```

With `outputMode: "chunks"` the `markdown` field is `null` and `chunks` holds objects like:

```json
{ "index": 3, "text": "## Results\n\n| Region | ...", "tokensEstimate": 212, "pageStart": 2, "pageEnd": 2, "headingPath": ["Annual Findings", "Results"] }
```

| Field | Meaning |
|---|---|
| `status`, `reason` | See the status table below. `reason` is `null` for `ok`. |
| `charged` | `true` only for `ok` rows. |
| `extraPageBlocks` | Number of `extra-pages-10` blocks charged for this PDF (0 unless you raised `maxPages` above 50). |
| `title`, `author`, `subject`, `keywords`, `creator`, `producer`, `createdAt`, `modifiedAt` | From the PDF information dictionary. Dates are ISO 8601. `null` when the file has none. |
| `pageCount` | Pages in the PDF. `pagesProcessed` is how many were converted. `truncated` is `true` when `maxPages` or the budget cut the document short. |
| `scannedLikely` | `true` when at least half of the processed pages have no text layer. `pagesWithoutText` lists them. |
| `garbledRatio` | Share of non-space characters that are replacement characters, private-use code points or control characters (0 to 1). A value above 0.02 adds the warning `GARBLED_TEXT_SUSPECTED`. |
| `headingCount`, `tableCount`, `listCount` | Blocks found. |
| `removedHeaderFooterLines` | Margin lines dropped as repeated headers, footers or page numbers. |
| `charCount`, `tokensEstimate` | Size of the text. Tokens are estimated (4 Latin characters, or 1 Korean, Japanese or Chinese character, per token), not counted with a specific tokenizer. |
| `pageStats` | Per page: `chars`, `hasText`, `columns` (1 or 2), `garbledRatio`. |
| `warnings` | `PAGE_LIMIT_REACHED`, `BUDGET_LIMITED_PAGES`, `PAGES_WITHOUT_TEXT_LAYER`, `GARBLED_TEXT_SUSPECTED`, `ROTATED_TEXT_SKIPPED`, `PAGE_UNREADABLE`, `PAGES_FIELD_DROPPED_ROW_TOO_LARGE`, `OUTPUT_SAVED_TO_KEY_VALUE_STORE`. |
| `markdown`, `text`, `chunks`, `pages` | The requested content. |
| `outputRecordKey` | Normally `null`. A row larger than about 8 MB moves its content to the run's key-value store under this key. |

The key-value store also holds `SUMMARY`: counts per status, pages processed, whether the run stopped early, and billing counts. It contains no document text and no URLs.

#### Status codes

| `status` | Meaning | Charged |
|---|---|---|
| `ok` | Text was extracted. | yes |
| `no_text` | No processed page has a text layer. Probably a scan; this Actor does no OCR. `reason` is `NO_TEXT_LAYER`. | no |
| `not_pdf` | The download is not a PDF (`NOT_A_PDF`). | no |
| `too_large` | Larger than `maxFileSizeMb` (`FILE_TOO_LARGE`). | no |
| `encrypted` | A password is needed to open it (`PASSWORD_REQUIRED`). PDFs that only restrict printing or copying open normally. | no |
| `unreachable` | DNS, connection or TLS failure, HTTP 4xx or 5xx, too many redirects. | no |
| `timeout` | The download or the conversion passed `timeoutPerPdfSecs` (`REQUEST_TIMEOUT`, `PDF_TIMEOUT`). | no |
| `parse_error` | The PDF structure is broken, or `pageRange` is invalid or selects no page. | no |
| `invalid_url` | Not a URL, a private or internal address, or a duplicate of an earlier input (`DUPLICATE_INPUT`). | no |
| `budget_stopped` | The run's maximum charge was reached; this URL was not requested. | no |

Reason codes: `INVALID_URL`, `UNSAFE_ADDRESS`, `DUPLICATE_INPUT`, `DNS_FAILED`, `CONNECTION_FAILED`, `TLS_ERROR`, `REQUEST_TIMEOUT`, `HTTP_4XX`, `HTTP_5XX`, `TOO_MANY_REDIRECTS`, `FILE_TOO_LARGE`, `NOT_A_PDF`, `PASSWORD_REQUIRED`, `PDF_PARSE_FAILED`, `PDF_TIMEOUT`, `INVALID_PAGE_RANGE`, `PAGE_RANGE_EMPTY`, `NO_TEXT_LAYER`, `BUDGET_LIMIT`, `INTERNAL_ERROR`.

### Pricing

Pay per event. You pay for results, not for runs that fail.

| Event | Price | When |
|---|---|---|
| `pdf` | **$0.003** | One PDF with status `ok`. Covers up to 50 processed pages. |
| `extra-pages-10` | **$0.0005** | Once per started block of 10 processed pages beyond the first 50. Only if you raise `maxPages` above 50. |

Examples: a 30-page PDF costs $0.003. With `maxPages: 200`, a 120-page PDF costs $0.003 + 7 x $0.0005 = $0.0065 (70 extra pages = 7 blocks). With the default `maxPages` of 50 the second event never happens: a longer PDF is cut at 50 pages and the row says `truncated: true`.

Pages are counted on what was actually converted (`pagesProcessed`), after `pageRange` and `maxPages`. Rows with any other status than `ok` are free. Platform usage and the Apify actor-start event are billed by Apify as usual.

**Spending limit.** Before each download the Actor reserves the most that PDF could cost. If the remaining budget of the run cannot cover it, the PDF is not requested and gets a free `budget_stopped` row; if it covers the base price but not all extra blocks, the PDF is converted up to the pages the budget allows (`truncated: true`, warning `BUDGET_LIMITED_PAGES`).

### How the Markdown is built

- **Reading order.** Text positions are grouped into lines. Two-column pages are detected from an empty vertical band in the middle of the page; lines that cross the band (titles, abstracts) split the page into sections that are read left column first, then right.
- **Headings.** The body size is the most common font size by character count. Lines at least 12% larger, in at most four size levels, become `#` to `####`. Short lines set in a bold font at body size become headings when bold text is not the norm in the document.
- **Lists.** Bullet glyphs (including Korean `□ ○ ▪ ㆍ`), `1.` `1)` `(1)`, `가.` and Roman numerals start list items; wrapped lines are joined to their item.
- **Paragraphs.** Lines are re-flowed. A new paragraph starts on a larger line gap than the document's line spacing, a first-line indent, or a short line that ends a sentence. Hyphenation at line ends is removed (`trans-` + `former`); hyphenated compounds that continue with another hyphen are kept.
- **Tables.** Consecutive lines whose text sits in the same vertical columns become a Markdown table. This uses text positions only.
- **Headers and footers.** Margin lines that repeat across pages and bare page numbers (Arabic and Roman) are removed.
- **CJK.** PDF.js is given its bundled CMaps and standard fonts. Hangul words are separated by the spaces the PDF actually contains; Han and kana are joined without spaces.

### Limits - read before you rely on it

- **No OCR.** Scanned or image-only pages produce no text. Check `pagesWithoutText` and `scannedLikely`.
- **Tables are heuristic.** Ruled tables without aligned text, merged cells and cells that wrap over several lines are not reliable: a wrapped cell becomes several rows. A block of aligned text such as an author list can be read as a table.
- **Layout.** Only one or two text columns are handled. Rotated text is skipped (`ROTATED_TEXT_SKIPPED`), vertical Japanese text is not supported, and text inside figures is returned as the PDF stores it.
- **Slides and forms.** Slide decks and forms have no prose structure; expect many short headings and table fragments.
- **Garbled text cannot always be detected.** `garbledRatio` counts replacement, private-use and control characters. A PDF whose fonts map glyphs to wrong but valid letters passes the check.
- **Missing spaces.** Where a PDF packs words together without space characters or clear gaps (condensed, justified Korean text, for example), PDF.js returns the words without a space and so do we. Spot checks of Korean government PDFs showed it in a minority of lines.
- **Hyphenation** at line ends is a guess: some real hyphens before a lowercase word are removed.
- **Equations, footnote markers and superscripts** come out as plain inline text.
- Password-protected PDFs are not opened. Files over `maxFileSizeMb` are not parsed. Memory: the default of 1024 MB is enough for typical documents; the Actor parses one PDF at a time.

### Responsible use

You are responsible for having the right to process the PDFs you submit and for the terms of the sites you fetch them from. The Actor fetches only the URLs you list, sends a descriptive `User-Agent`, and does not store documents beyond the run's dataset.

### Technical notes

Built on [PDF.js](https://github.com/mozilla/pdf.js) (`pdfjs-dist`, Apache-2.0) and the Apify SDK. See `THIRD_PARTY_NOTICES.md` in the source.

### For agents and MCP clients

- No credentials, cookies or API keys are needed; the PDFs must be public `http(s)` URLs.
- Every input URL gets one row with `status` (`ok`, `no_text`, `not_pdf`, `too_large`, `encrypted`, `unreachable`, `timeout`, `parse_error`, `invalid_url`, `budget_stopped`) and a `reason` code; `scannedLikely` and `garbledRatio` flag documents that need OCR or review (the Actor does no OCR).
- Rows are bounded: files over `maxFileSizeMb` (default 30) are refused, at most `maxPages` (default 50) are converted, and a row larger than about 8 MB moves its content to the key-value store (`outputRecordKey`).
- Cost is bounded before the run starts: `urls × $0.003` for up to 50 pages each, plus $0.0005 per extra block of 10 pages only if you raise `maxPages` above 50; only `ok` rows are charged.
- Use it from Claude, Cursor or any MCP client through the Apify MCP server (`https://mcp.apify.com`) — the tool arguments come from this Actor's input schema.

# Actor input Schema

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

Up to 500 public http(s) URLs of PDF files. Redirects are followed (each hop is checked again). URLs that point to private or internal addresses, use a custom port, or contain credentials are refused and not charged. The same URL listed twice is converted and charged once.

## `outputMode` (type: `string`):

markdown: one Markdown string with headings, lists and tables. text: the same reading order as plain text. chunks: the Markdown split into chunks of about chunkSize tokens, each with its page range and heading path. The price is the same for all modes.

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

Target size of one chunk in estimated tokens (about 4 Latin characters, or 1 Korean/Japanese/Chinese character, per token). It is an estimate, not the count of a specific tokenizer. Used only when outputMode is chunks.

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

Optional pages to convert, for example "1-5,8,10-". Empty means all pages, up to maxPages. A range that selects no page of the PDF gives status parse_error.

## `maxPages` (type: `integer`):

Most pages converted per PDF. The first 50 pages are included in the PDF price. If you raise this above 50, every started block of 10 pages beyond 50 costs an extra $0.0005 (event extra-pages-10). With the default of 50 no extra charge can occur; a longer PDF is cut at 50 pages and the row says truncated: true.

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

Larger files are not parsed and get status too_large (free). The download stops as soon as the limit is passed.

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

Adds a pages array with the plain text of each page. Per-page statistics (characters, garbledRatio, hasText) are always included.

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

Drops lines in the top or bottom margin that repeat on at least 40% of the pages (needs 3 or more pages). Bare page numbers in the margin are always dropped.

## `detectTables` (type: `boolean`):

Turns text laid out in aligned columns into Markdown tables. It uses text positions only: ruled tables without text alignment, merged cells and cells that wrap over several lines are not reliable.

## `pageMarkers` (type: `boolean`):

Inserts an HTML comment such as  where a page begins in the Markdown output.

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

Download and conversion of one PDF must finish within this time. Otherwise the row gets status timeout and is not charged.

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

How many PDFs are downloaded at the same time. Parsing itself runs one PDF at a time to keep memory bounded.

## Actor input object example

```json
{
  "urls": [
    "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
    "https://arxiv.org/pdf/1706.03762"
  ],
  "outputMode": "markdown",
  "chunkSize": 800,
  "maxPages": 50,
  "maxFileSizeMb": 30,
  "includePages": false,
  "removeHeadersFooters": true,
  "detectTables": true,
  "pageMarkers": false,
  "timeoutPerPdfSecs": 120,
  "maxConcurrency": 2
}
```

# Actor output Schema

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

One row per input URL with status, metadata, quality signals (garbledRatio, scannedLikely, per-page stats), the Markdown, text or chunks, and whether the row was charged.

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

Counts per status, pages processed, whether the run stopped early and why, and billing counts. Contains no document text and no URLs.

# 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",
        "https://arxiv.org/pdf/1706.03762"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("teal_blacksmith/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",
        "https://arxiv.org/pdf/1706.03762",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("teal_blacksmith/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",
    "https://arxiv.org/pdf/1706.03762"
  ]
}' |
apify call teal_blacksmith/pdf-to-markdown --silent --output-dataset

```

## MCP server setup

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