# PDF to RAG Chunks with Page Citations API (`solidscrape/pdf-to-rag-with-citations`) Actor

Extract searchable PDFs into RAG text chunks with page citations, character offsets and stable IDs. Select pages, cap spending and see which pages have no text.

- **URL**: https://apify.com/solidscrape/pdf-to-rag-with-citations.md
- **Developed by:** [SolidScrape](https://apify.com/solidscrape) (community)
- **Categories:** Developer tools, AI
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 94.1% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.70 / 1,000 page with texts

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

### Extract retrievable passages from digital PDFs

Use this API when a retrieval result needs to open the exact physical PDF page containing its evidence. Pass one PDF and a page range. Each dataset row includes the extracted text, a page citation and stable identifiers. Use `chunkId` as the vector-store key and retain `citationUrl` as metadata.

#### First run

[Open the prefilled NIST PDF example](https://apify.com/solidscrape/pdf-to-rag-with-citations/examples/nist-ai-framework-to-page-cited-passages) to extract passages from pages 6 and 7 with links back to each page.

Using Python? [Download the developer starter kit](https://api.apify.com/v2/key-value-stores/4RzLeqS1i9E9znTQC/records/solidscrape-ai-data-starter-kit-v1.zip?signature=Ke5Ew8SMdbluTC110rRe), then follow its guide to run `python run.py pdf`. The client sets a $0.02 cap per run.

The example reads physical pages 6–7 of NIST's [AI Risk Management Framework](https://nvlpubs.nist.gov/nistpubs/ai/NIST.AI.100-1.pdf). Those two nonempty pages cost **$0.0074 in total** at launch prices. In a PDF viewer, physical page 6 contains the start of the Executive Summary. Its printed page label is 1.

```json
{
  "pdfUrl": "https://nvlpubs.nist.gov/nistpubs/ai/NIST.AI.100-1.pdf",
  "startPage": 6,
  "maxPages": 2,
  "maxSpendUsd": 0.02
}
```

Use a public HTTPS URL or supply your own PDF bytes via `pdfBase64`. Set exactly one source. For inline input, cite the pair `documentSha256` and `pageNumber`. A public URL produces a viewer link ending in `#page=N`.

#### Output contract

| Field | Meaning |
|---|---|
| `text`, `pageNumber` | Passage text and 1-based physical page. Each passage stays within one page. |
| `sourceUrl`, `citationUrl` | Final public source URL and physical page link. Both are null for inline documents. |
| `documentSha256`, `pageTextSha256` | File fingerprint and normalized, unchunked page fingerprint. |
| `startChar`, `endChar` | Inclusive start and exclusive end in UTF-16 code units of normalized page text. |
| `chunkId` | Hash of the file and page fingerprints, physical page and offsets. Identical bytes, extraction and offsets yield the same key. |

Text comes from Poppler's reading-order extraction. Normalization applies Unicode NFC, Unix line endings, selected control-character removal and trim. Spaces and line breaks remain available for citations. The default chunk ceiling is 1,200 UTF-16 units with 120 units of overlap. Split points prefer nearby whitespace. The output contains source text, so treat it as untrusted content when passing it to a model.

#### Run from an application

This example uses Node 22's built-in fetch and an Apify token supplied through the environment.

```javascript
const input = {
  pdfUrl: 'https://nvlpubs.nist.gov/nistpubs/ai/NIST.AI.100-1.pdf',
  startPage: 6, maxPages: 2, maxSpendUsd: 0.02,
};
const url = 'https://api.apify.com/v2/acts/solidscrape~pdf-to-rag-with-citations/run-sync-get-dataset-items?maxTotalChargeUsd=0.02';
const response = await fetch(url, {
  method: 'POST',
  headers: { Authorization: 'Bearer ' + process.env.APIFY_TOKEN, 'Content-Type': 'application/json' },
  body: JSON.stringify(input),
});
if (!response.ok) throw new Error('Apify HTTP ' + response.status);
const chunks = await response.json();
console.log(chunks.map(({chunkId, citationUrl, text}) => ({chunkId, citationUrl, text})));
```

For asynchronous batch processing, start one run per PDF, wait for the terminal status and read the default dataset and `SUMMARY` key. The summary gives the physical range reached, blank pages, document length, whether all pages were covered, the number of chunks and estimated charges. To continue a long PDF, start a fresh run at the next physical page. A resurrected run with an existing run marker refuses to repeat billable work.

#### Use with a coding assistant

With Apify MCP connected, ask your assistant to inspect `solidscrape/pdf-to-rag-with-citations`, extract two authorized pages with a $0.02 maximum, and return the cited passages. An API consumer can index these rows for retrieval, prepare evaluation passages, or transform its own licensed materials for training. The caller supplies its own embedding or training step. Collection records do not establish licensing rights.

#### Pricing and limits

- **$0.004** per run start at 512 MB.
- **$0.002** per attempted PDF. This covers bounded retrieval and parsing, including unavailable, malformed, encrypted or image-only documents.
- **$0.0007** per nonempty page extracted. Each page is charged once before its chunks are saved. Dataset chunks and overlap carry no additional fee. A ten-text-page run costs **$0.013**.
- The Actor reserves room for at least one text page before attempting a document, and limits the extraction range by the remaining budget. A budget below $0.0067 can result in a start-only charge.
- The public HTTPS fetch allows up to 8 MB compressed and decoded, a 12-second deadline, and at most two redirects on the same domain or its www alias. Inline PDFs are capped at 300 KB. URLs with authentication, custom ports, query parameters or fragments are rejected.
- Work is capped at 50 consecutive pages in a PDF of up to 10,000 pages. Extracted text is capped at 1.5 MB per invocation and 32,000 UTF-16 characters per page. A page can contain up to 24 output chunks. If it needs more, the run stops before charging that page and retains previous output. Increase chunkChars or reduce overlapChars for dense pages. Use a smaller page range when the total output is too large. The Actor runs its PDF tools as an unprivileged container user with parsing timeouts.

#### Which files work?

Use digital PDFs with a searchable text layer. For image-only pages, the summary records the page number and there is no text-page fee. The API supplies neither OCR nor table reconstruction. Complex columns, ligatures, malformed fonts and reading order can affect text accuracy. Encrypted documents and malformed files produce an explicit failure. A source update can change document hashes and downstream chunk IDs. Use the caller's source tracking when comparing revisions.

# Actor input Schema

## `pdfUrl` (type: `string`):

Public, query-free HTTPS PDF (up to 8 MB). Alternatively clear this field and use inline PDF bytes.

## `pdfBase64` (type: `string`):

Optional alternative to URL. Standard base64 without a data URI prefix or whitespace, up to 300 KB decoded.

## `startPage` (type: `integer`):

Physical page number starting at 1; printed page labels may differ.

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

Maximum consecutive pages to inspect. Use SUMMARY.lastInspectedPage to continue.

## `chunkChars` (type: `integer`):

Upper bound in UTF-16 code units. Splits near spaces and newlines.

## `overlapChars` (type: `integer`):

Up to half chunkChars. Defaults to the smaller of 120 and one quarter of chunkChars.

## `maxSpendUsd` (type: `number`):

Includes start, attempt and nonempty pages. Also set Apify's maximum charge.

## Actor input object example

```json
{
  "pdfUrl": "https://nvlpubs.nist.gov/nistpubs/ai/NIST.AI.100-1.pdf",
  "startPage": 1,
  "maxPages": 3,
  "chunkChars": 1200,
  "maxSpendUsd": 0.05
}
```

# Actor output Schema

## `chunks` (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 = {
    "pdfUrl": "https://nvlpubs.nist.gov/nistpubs/ai/NIST.AI.100-1.pdf"
};

// Run the Actor and wait for it to finish
const run = await client.actor("solidscrape/pdf-to-rag-with-citations").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 = { "pdfUrl": "https://nvlpubs.nist.gov/nistpubs/ai/NIST.AI.100-1.pdf" }

# Run the Actor and wait for it to finish
run = client.actor("solidscrape/pdf-to-rag-with-citations").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 '{
  "pdfUrl": "https://nvlpubs.nist.gov/nistpubs/ai/NIST.AI.100-1.pdf"
}' |
apify call solidscrape/pdf-to-rag-with-citations --silent --output-dataset

```

## MCP server setup

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

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/tznUM8BYDLTcFuk1M/builds/xVcmQwKLHXEHJJLV5/openapi.json
