# PDF for RAG (`dear_enstatite/pdf-for-rag`) Actor

Turn public PDF URLs into clean, page-numbered text for RAG, embeddings and citations. Per-page text, character counts, empty-page detection, truncation flag and SHA-256 hashes for dedup. Failed PDFs are free.

- **URL**: https://apify.com/dear_enstatite/pdf-for-rag.md
- **Developed by:** [Musson Tools](https://apify.com/dear_enstatite) (community)
- **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 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 for RAG – Page-Aware PDF Text Extractor

Turn public PDF links into **clean, page-numbered text** ready for chunking, embeddings and citations. One dataset item per PDF, with every page kept separate so your RAG pipeline can cite "page 7" instead of "somewhere in the document".

- 📄 **Page-aware output**: `pages[] = {page, text, characters}` in reading order.
- 🔁 **Dedup and change detection**: SHA-256 of the PDF bytes (`pdf_sha256`) and of the extracted text (`text_sha256`).
- 🕳️ **Empty-page detection**: `empty_text_pages` lists pages with no embedded text (usually blank or scanned).
- ✂️ **Predictable size**: combined text is capped (default 100,000 characters) and `truncated` tells you when it was cut.
- 💸 **Failures are free**: dead links, non-PDFs, encrypted, oversized, too-long or scanned-only PDFs return an `ok: false` row with an error code and are **not charged**.
- ⚡ Fast and light: poppler `pdftotext`, no browser, no proxy, 256 MB memory.

### Who it's for

- RAG and LLM pipelines that need page numbers for citations or page-level chunking.
- AI agents calling Apify via MCP that need a quick, cheap "read this PDF" tool.
- Teams indexing reports, papers, forms, manuals, policies and filings.
- Anyone who wants to re-index only when a PDF actually changed (compare `pdf_sha256`).

### Input

| Field | Default | Description |
| --- | --- | --- |
| `pdfUrls` | – | Public `http(s)` links to PDF files (up to 1,000 per run, duplicates removed). |
| `maxPages` | 20 | PDFs with more pages are rejected (free). Max 200. |
| `maxFileSizeMb` | 5 | Larger downloads are stopped and rejected (free). Max 25. |
| `maxCharacters` | 100000 | Cap on combined text per PDF. Max 1,000,000. |
| `includeFullText` | true | Set to false to return only the `pages` array (smaller rows when you chunk by page). |

```json
{
  "pdfUrls": [
    "https://arxiv.org/pdf/1706.03762",
    "https://www.irs.gov/pub/irs-pdf/fw9.pdf"
  ],
  "maxPages": 20
}
```

### Output

```json
{
  "ok": true,
  "url": "https://www.irs.gov/pub/irs-pdf/fw9.pdf",
  "final_url": "https://www.irs.gov/pub/irs-pdf/fw9.pdf",
  "pdf_sha256": "…64 hex chars…",
  "bytes": 140815,
  "method": "poppler-pdftotext",
  "ocr_performed": false,
  "page_count": 6,
  "pages": [
    { "page": 1, "text": "W-9\n\nForm\n(Rev. March 2024)\nDepartment of the Treasury…", "characters": 5703 },
    { "page": 2, "text": "…", "characters": 8170 }
  ],
  "text": "W-9\n\nForm…",
  "text_sha256": "…64 hex chars…",
  "characters": 37820,
  "empty_text_pages": [],
  "truncated": false,
  "warnings": ["Embedded PDF text only. Images, handwriting, reading order and table structure are not verified."],
  "error": null,
  "message": null,
  "content_is_untrusted": true
}
```

- `text` is all pages joined with a blank line (`\n\n`).
- When the character cap is hit, pages are filled in order. Later pages may show `characters: 0` and `truncated` is `true`.
- `content_is_untrusted: true` is a reminder for LLM pipelines: treat PDF text as data, never as instructions.

The Output tab has two views: **Overview** (one row per PDF) and **Pages** (one row per page).

#### Error codes (all free)

`INVALID_URL`, `URL_NOT_ALLOWED` (private or internal addresses), `DOWNLOAD_FAILED`, `PDF_TOO_LARGE`, `INVALID_PDF`, `ENCRYPTED_PDF`, `PAGE_LIMIT`, `PAGE_DIMENSIONS`, `NO_EXTRACTABLE_TEXT` (scanned or image-only PDF), `EXTRACTION_TIMEOUT`, `EXTRACTION_FAILED`.

### Limits. Please read before buying.

- **No OCR.** Only text embedded in the PDF is extracted. Scanned pages come back empty and are listed in `empty_text_pages`. A fully scanned PDF returns `NO_EXTRACTABLE_TEXT` and is not charged.
- **No layout or table structure.** Tables come out as plain text lines. Multi-column reading order follows poppler's default and is not verified.
- **No images, Markdown or metadata** (title, author and so on).
- Public URLs only: no logins, cookies or paywalls. Password-protected PDFs are rejected.
- Defaults: 20 pages, 5 MiB, 100,000 characters per PDF (raise up to 200 pages, 25 MiB, 1,000,000 characters). Each page has a 5-second extraction time limit.

### Pricing

Pay per event:

| Event | Price |
| --- | --- |
| PDF processed (successful extraction) | **$0.003** ($3 per 1,000 PDFs) |
| Actor start (Apify standard, per GB memory) | $0.00005 |

Failed PDFs are never charged. Set **Maximum cost per run** in Apify and the Actor stops cleanly when it's reached.

### Use with AI agents (MCP)

```
https://mcp.apify.com/?tools=dear_enstatite/pdf-for-rag
```

Example prompt: *"Use pdf-for-rag to read https://arxiv.org/pdf/1706.03762 and quote the page where multi-head attention is defined."*

### Responsible use

Only process PDFs you have the right to download and use. The Actor doesn't bypass authentication, paywalls or DRM.

# Actor input Schema

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

Public http(s) links to PDF files. One dataset item is produced per URL. Duplicates are removed. Up to 1,000 URLs per run.

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

PDFs with more pages are rejected (free, error PAGE_LIMIT).

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

Downloads larger than this are stopped and rejected (free, error PDF_TOO_LARGE).

## `maxCharacters` (type: `integer`):

Combined text is capped at this length. Pages are filled in order; `truncated` is true if anything was cut.

## `includeFullText` (type: `boolean`):

Untick to return only the per-page `pages` array (smaller output when you chunk by page).

## Actor input object example

```json
{
  "pdfUrls": [
    "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
  ],
  "maxPages": 20,
  "maxFileSizeMb": 5,
  "maxCharacters": 100000,
  "includeFullText": true
}
```

# Actor output Schema

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

All dataset items (one per PDF), opened on the Overview view: status, page count, characters, empty pages, truncation, error and PDF hash.

## `pages` (type: `string`):

The same dataset opened on the Pages view: one row per PDF page with page number, character count and text, for chunking and citations.

# 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": [
        "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("dear_enstatite/pdf-for-rag").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": ["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("dear_enstatite/pdf-for-rag").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": [
    "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
  ]
}' |
apify call dear_enstatite/pdf-for-rag --silent --output-dataset

```

## MCP server setup

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

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/RFEwaQm8nBRgDIgfk/builds/KhLYUE4HTCIjIhYX8/openapi.json
