# PDF, DOCX & Image to Text and Markdown (OCR) (`brimfold/document-to-text-markdown`) Actor

Turn PDFs, Word DOCX files and scanned images into clean text and Markdown, one row per page. Uses the PDF text layer when there is one and Tesseract OCR only when needed, so you pay the OCR price only for scanned pages.

- **URL**: https://apify.com/brimfold/document-to-text-markdown.md
- **Developed by:** [Brimfold Studio](https://apify.com/brimfold) (community)
- **Categories:** AI, Automation
- **Security:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.46 / 1,000 ocr pages

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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, DOCX & Image to Text and Markdown (OCR)

Turn PDFs, Word documents and scanned images into clean text and Markdown. You get one row per page with the page text, a Markdown version, word and character counts and an OCR confidence score, plus one combined Markdown file per document. Good for RAG and LLM pipelines, search indexes, archive digitisation and data entry.

**Only process documents you have the right to use.** The Actor downloads the links you give it. Copyright and confidentiality stay with the document owner, and you are responsible for having the right to download, convert and store each document.

### Why this one

- **Text layer first, OCR only when needed.** For each PDF page the Actor reads the embedded text. Only pages with almost no text (scans) go to Tesseract OCR. Text-layer pages cost a quarter of the OCR price.
- **Markdown that keeps structure.** DOCX headings become `#` headings, lists stay lists, bold and italic are kept and tables become Markdown tables. PDF and OCR pages become clean paragraphs with broken hyphenation repaired.
- **Per-page rows.** Each row says how it was read (`text-layer`, `ocr` or `docx`), so you can filter low-confidence OCR pages.
- **Predictable cost.** Hard caps on documents, pages per document and file size. Skipped files are never charged.
- **Permissive open-source stack only.** No AGPL or GPL code (see Licences below).

### Supported files

| Type | How it is read | Rows |
|---|---|---|
| PDF | PDFium text layer per page; Tesseract OCR for pages without text (or every page with `ocrMode: always`) | One per page, up to `maxPagesPerDocument` |
| DOCX (Word 2007+) | python-docx: paragraphs, headings, lists, bold/italic, tables, in document order | One per document |
| PNG, JPEG, TIFF (multi-page too), BMP, GIF, WebP | Tesseract OCR | One per image frame |

Legacy `.doc`, password-protected PDFs and other formats are skipped with a reason (`unsupported-type`, `unreadable-document`) and are not charged.

### Input

| Field | Default | Notes |
|---|---|---|
| `documentUrls` | 2 public-domain samples | http/https links to the files |
| `ocrMode` | `auto` | `auto` = text layer first, OCR only pages without text. `always` = OCR every PDF page (use when the text layer is poor). `never` = text layer only; images are skipped |
| `ocrLanguages` | `["eng"]` | Up to 3 of eng, deu, fra, spa, ita, por, nld. Each extra language makes OCR slower |
| `ocrDpi` | 200 | 100 to 400. 300 helps small print but is slower |
| `maxPagesPerDocument` | 100 | Later pages are not processed or charged |
| `maxDocuments` | 50 | Hard cap per run |
| `maxFileSizeMb` | 50 | Bigger files are skipped, checked while downloading |
| `includeMarkdown` | true | Adds `markdown` to each row; the combined `.md` file is always saved |

### Output

```json
{
  "url": "https://upload.wikimedia.org/wikipedia/commons/1/1b/Federal_Register-Vol74No33.pdf",
  "fileName": "Federal_Register-Vol74No33.pdf",
  "documentType": "pdf",
  "pageNumber": 1,
  "pageCount": 2,
  "method": "text-layer",
  "text": "Federal Register / Vol. 74, No. 33 / Friday, February 20, 2009 / Rules and Regulations ...",
  "markdown": "Federal Register / Vol. 74, No. 33 / Friday, February 20, 2009 / Rules and Regulations ...",
  "charCount": 6378,
  "wordCount": 951,
  "ocrConfidence": null,
  "ocrLanguages": null,
  "processingSecs": 0.01,
  "markdownFileKey": "0001-Federal_Register-Vol74No33.pdf.md",
  "markdownFileUrl": "https://api.apify.com/v2/key-value-stores/<store>/records/0001-Federal_Register-Vol74No33.pdf.md",
  "processedAt": "2026-11-02T19:56:52Z"
}
```

`ocrConfidence` is Tesseract's mean word confidence (0 to 100) for OCR pages. The `RUN-SUMMARY` record in the key-value store lists skipped links with reasons, OCR CPU and wall time per page, and the charge counts.

### Pricing

Pay per event, no platform usage added:

| Event | Price | When |
|---|---|---|
| `ocr-page` | $0.002 ($2 per 1,000) | A page or image frame whose text came from OCR |
| `text-page` | $0.0005 ($0.50 per 1,000) | A PDF page read from its text layer, or one DOCX document |
| Actor start | $0.00005 | Once per run |

Examples: a 40-page digital PDF costs $0.02. A 40-page scan costs $0.08. 1,000 scanned pages cost $2. A page that OCR runs on is charged even if no text is found on it (the OCR work still runs). In `auto` mode a PDF that already has a poor text layer (for example from an old scanner) is read as text; use `always` for those.

### Security, terms and rate limits

- **Private networks are blocked.** Links that resolve to private, loopback, link-local, carrier-grade NAT, multicast or reserved addresses (for example 127.0.0.1, 10.x, 169.254.169.254, localhost) are refused, on every redirect hop too. The connection is pinned to the address that was checked.
- **robots.txt is respected** (RFC 9309) with the user-agent token `BrimfoldStudio-DocToText`, including `Crawl-delay` (up to 30 s). Links blocked by robots.txt are skipped.
- **Polite fetching:** at most 2 requests at a time per host with a short gap, retries with back-off on 429 and 5xx, `Retry-After` honoured.
- No logins, cookies or captcha solving of any kind. Only use documents the site's terms let you download.
- Files are downloaded to a temporary folder inside the run and deleted after conversion. Only the extracted text and Markdown are stored.

### Licences

All processing libraries are permissively licensed. **No PyMuPDF or other AGPL/GPL code is used.**

| Component | Use | Licence |
|---|---|---|
| [pypdfium2](https://github.com/pypdfium2-team/pypdfium2) | PDF text layer and page rendering | Apache-2.0 or BSD-3-Clause |
| [PDFium](https://pdfium.googlesource.com/pdfium/) (bundled in pypdfium2) | PDF engine | BSD-3-Clause (Apache-2.0 parts) |
| [Tesseract OCR](https://github.com/tesseract-ocr/tesseract) 5 and its language data (Debian packages) | OCR | Apache-2.0 |
| [Leptonica](http://www.leptonica.org/) | Image library used by Tesseract | BSD-2-Clause style |
| [pytesseract](https://github.com/madmaze/pytesseract) | Python wrapper for Tesseract | Apache-2.0 |
| [python-docx](https://github.com/python-openxml/python-docx) | DOCX reading | MIT |
| [lxml](https://lxml.de/) (python-docx dependency) | XML | BSD-3-Clause |
| [Pillow](https://python-pillow.org/) | Images | MIT-CMU (HPND) |
| [httpx](https://www.python-httpx.org/) | Downloads | BSD-3-Clause |
| [Apify SDK for Python](https://github.com/apify/apify-sdk-python) | Actor runtime | Apache-2.0 |

### FAQ

**Is handwriting supported?** Not well. Tesseract is built for printed text.

**How fast is it?** Measured on Apify at 1 GB: about 0.8 s per typical scanned page at 200 DPI and about 3.5 s per dense three-column page at 300 DPI. Text-layer pages take a few hundredths of a second. More memory does not make OCR faster (it runs one page at a time on one core), so 1 GB is the best value.

**Can I get the whole document as one file?** Yes. Each document's combined Markdown is in the run's key-value store under `markdownFileKey`. `markdownFileUrl` needs your API token unless you share the store.

Made by Brimfold Studio. Default samples: a US Federal Register issue (US government work, public domain, via Wikimedia Commons) and the Tesseract project's `phototest.tif` test image (Apache-2.0).

# Actor input Schema

## `documentUrls` (type: `array`):

Links to PDF, DOCX or image files (PNG, JPEG, TIFF, BMP, GIF, WebP). Only process documents you have the right to use.

## `ocrMode` (type: `string`):

Auto reads a PDF page's embedded text and runs OCR only when the page has almost no text (a scan). Images always need OCR.

## `ocrLanguages` (type: `array`):

Languages in the scanned pages, up to 3 (extra ones are ignored). Each extra language makes OCR slower; English alone is fastest.

## `ocrDpi` (type: `integer`):

Resolution PDF pages are rendered at for OCR. 200 suits most scans; 300 helps small print but is slower.

## `maxPagesPerDocument` (type: `integer`):

Pages after this are not processed or charged.

## `maxDocuments` (type: `integer`):

Hard cap on documents processed in the run.

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

Larger files are skipped (not charged).

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

Add a Markdown version of each page to the rows. A combined Markdown file per document is always saved to the key-value store.

## Actor input object example

```json
{
  "documentUrls": [
    "https://upload.wikimedia.org/wikipedia/commons/1/1b/Federal_Register-Vol74No33.pdf",
    "https://raw.githubusercontent.com/tesseract-ocr/test/main/testing/phototest.tif"
  ],
  "ocrMode": "auto",
  "ocrLanguages": [
    "eng"
  ],
  "ocrDpi": 200,
  "maxPagesPerDocument": 100,
  "maxDocuments": 50,
  "maxFileSizeMb": 50,
  "includeMarkdown": true
}
```

# Actor output Schema

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

No description

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

No description

# 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 = {
    "documentUrls": [
        "https://upload.wikimedia.org/wikipedia/commons/1/1b/Federal_Register-Vol74No33.pdf",
        "https://raw.githubusercontent.com/tesseract-ocr/test/main/testing/phototest.tif"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("brimfold/document-to-text-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 = { "documentUrls": [
        "https://upload.wikimedia.org/wikipedia/commons/1/1b/Federal_Register-Vol74No33.pdf",
        "https://raw.githubusercontent.com/tesseract-ocr/test/main/testing/phototest.tif",
    ] }

# Run the Actor and wait for it to finish
run = client.actor("brimfold/document-to-text-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 '{
  "documentUrls": [
    "https://upload.wikimedia.org/wikipedia/commons/1/1b/Federal_Register-Vol74No33.pdf",
    "https://raw.githubusercontent.com/tesseract-ocr/test/main/testing/phototest.tif"
  ]
}' |
apify call brimfold/document-to-text-markdown --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,brimfold/document-to-text-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/1dmLhdMeLXHqzmmkv/builds/nEFLzahRGLZIt5DKh/openapi.json
