# PDF Text Extractor - PDF to Text for AI, RAG & Search (`optimistical_lectern/pdf-text-extractor`) Actor

Turn PDF files into clean text. Give it PDF URLs and get the full text, optional per-page text, page count, word count and document metadata (title, author, dates). Flags scanned PDFs that contain no text layer. Built for feeding documents to LLMs, RAG pipelines and search indexes.

- **URL**: https://apify.com/optimistical_lectern/pdf-text-extractor.md
- **Developed by:** [Ivan Honer](https://apify.com/optimistical_lectern) (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 pdfs

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 Text Extractor: PDF to Text for AI, RAG & Search

Turn PDF files into **clean text**. Give it PDF links and get back the full text, page-by-page text if you want it, the page and word count, and the document's metadata. Built for feeding documents to LLMs, RAG pipelines and search indexes.

- ✅ **Reading order preserved**: lines and paragraphs are rebuilt from the page layout, not dumped as fragments
- ✅ **Page-by-page text** for citations and chunking, or page markers inside the full text
- ✅ **Metadata**: title, author, subject, keywords, producer, created and modified dates
- ✅ **Flags scanned PDFs** that have no text layer, so you know which ones need OCR
- ✅ **Opens password-protected PDFs** when you give the password
- ✅ **Failed downloads and non-PDF links are free**

### What does PDF Text Extractor do?

For every URL in your list it:

1. Downloads the file, following redirects, and checks it really is a PDF.
2. Reads the text layer of every page (or up to your page limit) with Mozilla's PDF.js engine.
3. Rebuilds lines and paragraph breaks from the positions of the text on the page.
4. Returns the full text, optional per-page text, counts and metadata as one row per PDF.

### Use cases

- 🤖 **RAG and AI assistants.** Get clean text, with page numbers, from reports, manuals and filings to embed and search.
- 📚 **Search indexes.** Index the content of PDF libraries, product sheets or regulations.
- 🧾 **Document processing.** Pull the text out of forms, contracts and invoices for downstream parsing.
- 🔬 **Research.** Batch-extract text from papers and reports for analysis.
- 🗂️ **Archive triage.** Find out which files in a collection are scanned images that need OCR.

### What data can you get?

| Field | What it is |
|---|---|
| `url`, `finalUrl` | The link you gave, and where it ended up after redirects |
| `text` | The full extracted text |
| `pages` | `[{ page, text }]` for every page (switch on **Also return text page by page**) |
| `pageCount`, `pagesExtracted`, `truncated` | Pages in the file, pages read, and whether the page limit cut it short |
| `wordCount`, `characterCount`, `fileSizeBytes` | Size measures |
| `likelyScanned` | `true` when there is little or no text layer, which usually means a scan |
| `metadata.title`, `.author`, `.subject`, `.keywords`, `.creator`, `.producer` | Document properties |
| `metadata.createdDate`, `.modifiedDate`, `.pdfVersion` | Dates in ISO 8601, and the PDF version |
| `status`, `error` | See [Statuses and errors](#statuses-and-errors) |

### How to use it

1. Click **Try for free** (or **Start**) at the top of this page.
2. Paste direct links to PDF files into **PDF URLs**, one per line.
3. Switch on **Also return text page by page** if you need page numbers for citations or chunking.
4. Press **Start**.
5. Download the results from the **Output** tab, or pass them to your embedding or indexing step.

### Input examples

**A few public PDFs.**

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

**For RAG: per-page text, with long documents capped.**

```json
{
  "urls": ["https://example.com/annual-report-2026.pdf"],
  "includePages": true,
  "maxPagesPerPdf": 200
}
```

**A password-protected file.**

```json
{
  "urls": ["https://example.com/protected.pdf"],
  "password": "the-file-password"
}
```

### Output example

```json
{
  "url": "https://www.irs.gov/pub/irs-pdf/fw9.pdf",
  "status": "ok",
  "finalUrl": "https://www.irs.gov/pub/irs-pdf/fw9.pdf",
  "fileSizeBytes": 140815,
  "pageCount": 6,
  "pagesExtracted": 6,
  "truncated": false,
  "likelyScanned": false,
  "characterCount": 37974,
  "wordCount": 6284,
  "metadata": {
    "title": "Form W-9 (Rev. March 2024)",
    "author": "SE:W:CAR:MP",
    "subject": "Request for Taxpayer Identification Number and Certification",
    "keywords": "Fillable",
    "creator": "Designer 6.5",
    "producer": "Designer 6.5",
    "createdDate": "2024-03-06T08:18:13Z",
    "modifiedDate": "2024-03-06T08:18:13Z",
    "pdfVersion": "1.7"
  },
  "text": "Form W-9\n(Rev. March 2024)\n\nRequest for Taxpayer\nIdentification Number and Certification\n\nDepartment of the Treasury ..."
}
```

### Statuses and errors

Every URL gets a row.

| `status` / `error` | Meaning | Charged? |
|---|---|---|
| `ok` | Text extracted. If `likelyScanned` is `true`, the PDF is probably a scan and has little text | Yes |
| `error`: `The URL did not return a PDF file` | The link points at a web page or another file type | No |
| `error`: `HTTP 404`, `HTTP 403`... | The server refused the download | No |
| `error`: `File is larger than the 50 MB limit` | Raise **Maximum file size** (up to 100 MB) | No |
| `error`: `The PDF is password protected` | Give the password in **Password** | No |
| `error`: `The file is not a readable PDF` | The file is damaged | No |
| `error`: `Download timed out` | The server was too slow; raise **Download timeout** | No |
| `invalid_input` | Not a URL | No |

### How much does it cost?

You pay per PDF extracted. Failed downloads, non-PDF links and oversized files are free, and platform usage is included.

| PDFs | Price on the Free and Bronze tiers |
|---|---|
| 100 | $0.40 |
| 1,000 | $4.00 |
| 10,000 | $40.00 |

Larger Apify plans pay less per PDF: 15% less on Silver, and 25% less on Gold and above.

### FAQ

#### Can I use it through the API?

Yes. For a few files, the synchronous endpoint returns the text in one request:

```bash
curl -X POST "https://api.apify.com/v2/acts/optimistical_lectern~pdf-text-extractor/run-sync-get-dataset-items?token=YOUR_APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"urls": ["https://www.irs.gov/pub/irs-pdf/fw9.pdf"]}'
```

JavaScript:

```js
import { ApifyClient } from 'apify-client';

const client = new ApifyClient({ token: 'YOUR_APIFY_TOKEN' });
const run = await client.actor('optimistical_lectern/pdf-text-extractor').call({ urls: ['https://www.irs.gov/pub/irs-pdf/fw9.pdf'], includePages: true });
const { items } = await client.dataset(run.defaultDatasetId).listItems();
```

Python:

```python
from apify_client import ApifyClient

client = ApifyClient("YOUR_APIFY_TOKEN")
run = client.actor("optimistical_lectern/pdf-text-extractor").call(run_input={"urls": ["https://www.irs.gov/pub/irs-pdf/fw9.pdf"], "includePages": True})
items = client.dataset(run["defaultDatasetId"]).list_items().items
```

#### Can AI agents use it?

Yes. It runs with limited permissions, so it needs no approval step. Add it to Claude, Cursor or any other MCP client through Apify's MCP server at `mcp.apify.com`, using the Actor name `optimistical_lectern/pdf-text-extractor`. It is a good fit for an agent that needs to read a PDF linked from a web page.

#### Does it do OCR?

No. It reads the text layer that most digitally created PDFs have. For scanned PDFs it returns little or no text and sets `likelyScanned: true`, so you can route those files to an OCR tool.

#### How are tables handled?

Tables come out as lines of text in reading order, not as structured rows and columns.

#### What about multi-column layouts?

Text is read in the order the PDF stores it, which is the reading order for almost all documents. Unusual layouts can occasionally interleave columns.

#### Can I upload files instead of giving URLs?

Upload the files anywhere that gives a direct link (for example an Apify key-value store, S3 or a public cloud folder) and pass those links.

#### Something looks wrong?

Open an issue on the **Issues** tab with a link to the PDF. Every report is read.

### Related tools

- [📇 Website Contact Extractor](https://apify.com/optimistical_lectern/website-contact-extractor): emails, phones and social profiles from websites
- [🌐 Domain WHOIS, DNS & Email Security](https://apify.com/optimistical_lectern/domain-whois-dns-lookup): registration and email-security data for domains
- [💼 Google Jobs Scraper](https://apify.com/optimistical_lectern/google-jobs-scraper): job listings with salaries and apply links

# Actor input Schema

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

Direct links to PDF files, one per line.

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

Adds a `pages` array with the text of each page, for citations and chunking.

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

Inserts a line such as `--- Page 3 ---` before each page in `text`.

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

Stop after this many pages. 0 means the whole document.

## `password` (type: `string`):

Only needed for password-protected PDFs. Applied to every URL in this run.

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

Larger files are skipped and not charged.

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

How many files to process at the same time.

## `timeoutSecs` (type: `integer`):

Give up on a download after this long.

## Actor input object example

```json
{
  "urls": [
    "https://www.irs.gov/pub/irs-pdf/fw9.pdf"
  ],
  "includePages": false,
  "pageMarkers": false,
  "maxPagesPerPdf": 0,
  "maxFileSizeMb": 50,
  "maxConcurrency": 4,
  "timeoutSecs": 60
}
```

# Actor output Schema

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

One item per input, as listed in the README.

# 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.irs.gov/pub/irs-pdf/fw9.pdf"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("optimistical_lectern/pdf-text-extractor").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.irs.gov/pub/irs-pdf/fw9.pdf"] }

# Run the Actor and wait for it to finish
run = client.actor("optimistical_lectern/pdf-text-extractor").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.irs.gov/pub/irs-pdf/fw9.pdf"
  ]
}' |
apify call optimistical_lectern/pdf-text-extractor --silent --output-dataset

```

## MCP server setup

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

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/bVQybIYRcG4sdvXgi/builds/2qu0XfM6CTmVKGEd5/openapi.json
