# PDF & Word (DOCX) to Markdown Converter for LLMs and RAG (`geeky_goth_gamer/pdf-docx-to-markdown`) Actor

Convert PDF and Word (.docx) files from URLs into clean Markdown for LLMs, RAG and summarising. Input: file URLs. Output: Markdown per document with headings, tables, page markers and optional chunks. $0.003 per page.

- **URL**: https://apify.com/geeky_goth_gamer/pdf-docx-to-markdown.md
- **Developed by:** [Chris Day](https://apify.com/geeky_goth_gamer) (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 page converteds

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 & DOCX to Markdown for AI/RAG

Turn links to PDF and Word (.docx) files into clean, structured Markdown that is ready for LLMs, vector databases and RAG pipelines. Optionally split each document into heading-aware chunks.

### When an AI agent should use this

Use `geeky_goth_gamer/pdf-docx-to-markdown` when:

- You have a link to a PDF or Word (.docx) file and need its text as Markdown to read, summarise, quote or index.
- You are building RAG or search over reports, papers, contracts, manuals or policies (set `chunkSize` for ready-made chunks).
- You need page numbers for citations (`includePageMarkers: true`).

Don't use it for:

- HTML web pages (use a web page to Markdown Actor) or scanned PDFs that need OCR.

**Example input:**

```json
{
  "urls": [
    "https://arxiv.org/pdf/1706.03762"
  ],
  "chunkSize": 4000,
  "maxPagesPerDocument": 20
}
```

**Output:** One dataset item per document: `markdown`, `pageCount`, `title`, `warnings`, optional `chunks`, and `billablePages`.

**Cost:** $0.003 per PDF page (20 pages = $0.06). Failed files are free.

**Call it from an agent:**

- Apify MCP server: add `https://mcp.apify.com/?tools=geeky_goth_gamer/pdf-docx-to-markdown` to your MCP client; the tool is `geeky_goth_gamer--pdf-docx-to-markdown`. Or use `call-actor` with `"actor": "geeky_goth_gamer/pdf-docx-to-markdown"`.
- Python: `ApifyClient(token).actor("geeky_goth_gamer/pdf-docx-to-markdown").call(run_input=...)`, then read `client.dataset(run["defaultDatasetId"]).list_items().items`.
- HTTP: `POST https://api.apify.com/v2/acts/geeky_goth_gamer~pdf-docx-to-markdown/run-sync-get-dataset-items?token=YOUR_TOKEN` with the input JSON as the body.

### What it does

- **PDF → Markdown** with real structure: `#` headings worked out from font sizes and bold numbered sections, paragraphs re-joined across line breaks, hyphenated words rejoined, bullet lists, and ruled tables turned into Markdown tables.
- **Two-column layouts** (research papers, reports) are read column by column, in the right order.
- **Noise removal:** running headers, footers, page numbers and rotated margin stamps (such as the arXiv sidebar) are dropped.
- **DOCX → Markdown:** headings, lists, tables, bold and italics, links, and image placeholders. The title comes from the document properties.
- **RAG chunking (optional):** chunks of up to N characters split at headings, then paragraphs, then sentences, with optional overlap. Each chunk carries its `headingPath` (e.g. `["3 Model Architecture", "3.2 Attention"]`).
- **Safe by design:** only public `http(s)` links are fetched. Links to private, internal or cloud-metadata addresses are refused, every redirect is re-checked, and downloads are capped in size and time. Each document is converted in a separate memory-limited process, so one malformed file cannot crash the run.

### Input

| Field | Default | Notes |
|---|---|---|
| `urls` (required) | — | Public links to PDF or DOCX files. Up to 1,000 per run. Duplicates are removed. |
| `chunkSize` | 0 | 0 = no chunks; otherwise 200–50,000 characters. |
| `chunkOverlap` | 0 | Up to half of `chunkSize`. |
| `removeHeadersFooters` | true | PDF only. |
| `detectTables` | true | PDF only. |
| `includePageMarkers` | false | PDF only. Adds `<!-- page N -->` so you can cite page numbers. |
| `includeImagePlaceholders` | true | DOCX only. Image data is never included. |
| `maxPagesPerDocument` | 500 | Only the first N pages are converted and billed (1–3,000). |
| `maxFileSizeMb` | 50 | 1–200. Larger files are skipped and not billed. |
| `timeoutSecondsPerDocument` | 300 | 10–1,800. |

Example:

```json
{
  "urls": ["https://arxiv.org/pdf/1706.03762"],
  "chunkSize": 1500,
  "chunkOverlap": 100
}
```

Invalid input stops the run straight away with a clear message (for example `Invalid input: "chunkOverlap" must be at most half of "chunkSize"`), and nothing is charged.

### Output

One dataset item per link:

```json
{
  "url": "https://arxiv.org/pdf/1706.03762",
  "status": "ok",
  "finalUrl": "https://arxiv.org/pdf/1706.03762",
  "fileName": "1706.03762v7.pdf",
  "fileType": "pdf",
  "fileSizeBytes": 2215244,
  "pageCount": 15,
  "title": "Attention Is All You Need",
  "markdown": "# Attention Is All You Need\n\n...",
  "chunks": [{"index": 0, "text": "...", "headingPath": ["Abstract"]}],
  "characterCount": 39527,
  "wordCount": 6373,
  "warnings": ["921 rotated/vertical text fragment(s) (e.g. margin stamps) were skipped."],
  "billablePages": 15,
  "durationSeconds": 2.9
}
```

Failed links produce `{"url": ..., "status": "error", "error": "<plain-English reason>", "billablePages": 0}` and are never charged.

### Pricing

Pay per event. You pay only for pages successfully converted:

- **Page converted:** $0.003 per PDF page. DOCX files have no pages, so they are billed per 3,000 characters of output (at least one).
- **Actor start:** Apify's standard start fee ($0.00005 per run per GB of memory).

There is no per-document fee. Failed, empty, scanned-image-only and refused files are free. The Actor respects your **maximum cost per run**: it never converts more pages than your budget covers, and it stops cleanly when the budget runs out.

Examples: a 15-page paper costs about $0.045, and 1,000 ten-page reports cost about $30.

### Limitations

- **No OCR.** Scanned PDFs (images of text) return a warning and are not billed.
- **Complex forms** (for example tax forms with many boxes) come out readable but untidy.
- **Tables:** only ruled tables are detected. Borderless tables come out as text.
- **Rotated text** (vertical margin labels) is skipped on purpose.
- **Not supported:** password-protected PDFs, legacy `.doc` files and other formats; these return a clear error.
- The SSRF guard checks every address a link resolves to and every redirect. A hostile DNS server that changes its answer between the check and the connection (DNS rebinding) is a residual, documented risk, which is limited by the platform's network isolation.

### Open-source components

pdfplumber and pdfminer.six (MIT), mammoth (BSD-2), markdownify (MIT), httpx (BSD-3), Apify SDK (Apache-2.0). No AGPL components.

### Local development

```bash
python -m venv venv && . venv/bin/activate && pip install -r requirements.txt pytest reportlab python-docx
python -m pytest -p no:asyncio      # SKIP_NETWORK=1 to skip tests that download real documents
apify run                           # uses storage/key_value_stores/default/INPUT.json
```

# Actor input Schema

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

REQUIRED. Public http(s) links that download a PDF or Word .docx file, e.g. \["https://arxiv.org/pdf/1706.03762"]. Up to 1,000 per run; duplicates are removed. Not for HTML web pages (use a web-page-to-markdown Actor) or scanned images (no OCR).

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

0 = no chunks. Otherwise split the Markdown into chunks of at most this many characters, preferring heading and paragraph boundaries. Each chunk includes its heading path.

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

Characters repeated from the end of the previous chunk. At most half of the chunk size.

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

PDF only. Drops small text that repeats in the top or bottom margin on most pages.

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

PDF only. Ruled tables become Markdown tables; turn off to keep table text as plain paragraphs.

## `includePageMarkers` (type: `boolean`):

PDF only. Adds  comments so you can cite page numbers.

## `includeImagePlaceholders` (type: `boolean`):

DOCX only. Keeps ![alt](image) placeholders where images were. Image data is never included.

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

Only the first N pages of each PDF are converted and billed. Use a small value (e.g. 5) to preview a long document cheaply.

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

Files larger than this are skipped with an error and are not billed.

## `timeoutSecondsPerDocument` (type: `integer`):

Time limit for downloading plus converting one document; slower documents fail with an error and are not billed.

## Actor input object example

```json
{
  "urls": [
    "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
  ],
  "chunkSize": 0,
  "chunkOverlap": 0,
  "removeHeadersFooters": true,
  "detectTables": true,
  "includePageMarkers": false,
  "includeImagePlaceholders": true,
  "maxPagesPerDocument": 500,
  "maxFileSizeMb": 50,
  "timeoutSecondsPerDocument": 300
}
```

# Actor output Schema

## `results` (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 = {
    "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("geeky_goth_gamer/pdf-docx-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("geeky_goth_gamer/pdf-docx-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 geeky_goth_gamer/pdf-docx-to-markdown --silent --output-dataset

```

## MCP server setup

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