# Website & PDF to RAG Chunks (`neighborly_ulexite/website-pdf-to-rag-chunks`) Actor

Crawl any website (JavaScript too) or PDF (scanned too) and get clean, heading-aware chunks ready for embeddings and vector databases (Pinecone, Qdrant, Weaviate, pgvector, LangChain, LlamaIndex).

- **URL**: https://apify.com/neighborly_ulexite/website-pdf-to-rag-chunks.md
- **Developed by:** [Khushbu Shukla](https://apify.com/neighborly_ulexite) (community)
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $2.00 / 1,000 pages processed

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/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

## Website & PDF to RAG Chunks

Turn any website (including JavaScript apps) or PDF (including scanned documents) into **clean, ready-to-embed chunks** for your AI chatbot, RAG pipeline or vector database. No HTML noise, no cookie banners, no navigation menus. You get the real content, split along its headings, with the metadata your retriever needs.

### What does it do?

1. **Crawls** a website (using its links and `sitemap.xml`) or downloads PDF files you link directly.
   - **JavaScript sites** (React, Vue, Angular, Next.js apps): pages that come back empty or blocked are automatically re-opened in a real Chrome browser. Simple pages stay fast and cheap.
   - **Scanned PDFs**: pages without a text layer are read with OCR in 16 languages.
   - **PDF tables** are rebuilt as real Markdown tables, both gridded tables and academic tables that only use horizontal rules. Tables too big for one chunk are split by rows, with the header repeated in every piece.
   - **PDF headings** are found from numbering ("3.2 Attention"), font size and bold type, so every chunk knows its section. Two-column pages are read column by column, and sideways margin stamps are removed.
2. **Extracts** only the main content: navigation, footers, sidebars, cookie banners, share buttons and scripts are removed. Headings, lists, tables and code blocks are kept as Markdown.
3. **Chunks** the text **along headings**, so a chunk never mixes two unrelated sections. Paragraphs, tables and code blocks are not cut in half.
4. **Adds context** to every chunk (`Page title > Section > Subsection`), which noticeably improves retrieval quality.
5. Outputs records you can send straight to **Pinecone, Qdrant, Weaviate, pgvector, Chroma, LangChain or LlamaIndex**.

### Why use it instead of a general web scraper?

| | General scrapers | This Actor |
|---|---|---|
| Removes menus, footers, cookie banners | Sometimes | ✅ |
| Splits by headings, not every N characters | ❌ | ✅ |
| Never cuts a table or code block in half | ❌ | ✅ |
| Section path + page title on every chunk | ❌ | ✅ |
| PDFs with page numbers on each chunk | ❌ | ✅ |
| PDF tables kept as tables, with headers on every piece | ❌ | ✅ |
| Screenshot of every PDF table, linked from its chunks | ❌ | ✅ |
| JavaScript sites, browser only when needed | Usually all-or-nothing | ✅ |
| OCR for scanned PDF pages only | ❌ | ✅ |
| Skips duplicate and near-empty pages (not charged) | ❌ | ✅ |

### Use cases

- **Customer support chatbots** trained on your help center and docs
- **"Chat with the docs"** for any library, API or product
- **Internal knowledge bases** built from policy PDFs and manuals
- **AI agents** that need fresh, structured web knowledge
- **Fine-tuning and evaluation datasets** from clean web text

### Input

The only required field is **Start URLs**: websites and/or direct links to PDF files.

| Field | Default | What it does |
|---|---|---|
| Start URLs | | Websites to crawl or PDF links |
| Max pages | 100 | Total pages/PDFs to process |
| Max crawl depth | 3 | How far to follow links (0 = only start URLs) |
| Output | chunks | `chunks` for vector DBs, `documents` for one Markdown record per page |
| Chunk size (tokens) | 500 | Target chunk size (≈4 characters per token) |
| Chunk overlap (tokens) | 50 | Shared context between neighbouring chunks |
| Only crawl / never crawl URLs matching | | Glob filters, e.g. `https://site.com/docs/**` |
| Stay inside the start URL's section | off | Start at `/docs/guide` to crawl only `/docs/guide/...` |
| Use sitemap.xml | on | Faster, more complete discovery |
| JavaScript rendering | Auto | `Auto` = browser only when needed, `Always`, or `Never` |
| OCR for scanned PDFs | Auto | `Auto` = only pages without text, `Always`, or `Off` |
| OCR languages | English | 16 languages, pick several for mixed documents |
| Max OCR pages per run | 500 | Safety cap on OCR work |
| Respect robots.txt | on | Polite crawling |

### Output

One record per chunk:

```json
{
  "id": "9f2c1e7a0b3d4c55-3",
  "url": "https://docs.example.com/billing",
  "title": "Billing",
  "sourceType": "html",
  "section": "Billing > Retries > Idempotency",
  "chunkIndex": 3,
  "chunkCount": 6,
  "pageStart": null,
  "pageEnd": null,
  "text": "Use idempotency keys for safe retries...",
  "textForEmbedding": "Billing > Retries > Idempotency\n\nUse idempotency keys for safe retries...",
  "tokenEstimate": 412,
  "language": "en",
  "renderedWithBrowser": false,
  "ocrPages": null,
  "tableImages": [{ "page": 7, "imageUrl": "https://api.apify.com/v2/key-value-stores/…/records/table-…-p7-1.png" }],
  "crawledAt": "2026-12-01T18:00:00+00:00"
}
```

- Embed **`textForEmbedding`** and store **`text`** for display. That's the recommended pattern.
- For PDFs, `pageStart`/`pageEnd` tell you which pages a chunk came from, so your chatbot can cite "page 12".
- `tableImages` lists a PNG screenshot of every PDF table in the chunk (`page`, `imageUrl`). Show it next to answers, or pass it to a multimodal model when exact layout matters. Turn this off with **Save a screenshot of every PDF table**.
- `id` is stable for the same content, so re-runs can upsert instead of duplicating.

A run summary (pages processed, skipped, errors) is saved in the key-value store under `OUTPUT`.

### Pricing

You pay **per page processed**: one web page, or one PDF page, is one unit. Two small add-ons apply only when used:

- **JavaScript render**: a page that needed a real browser
- **OCR page**: a scanned PDF page read with OCR

Pages that are empty, duplicated, blocked or failed are **not charged**. In Auto mode you never pay for a browser or OCR on pages that don't need them. Set a maximum cost per run in Apify Console and the Actor stops cleanly when it is reached.

### Integrations

- **LangChain / LlamaIndex**: use the Apify dataset loader and map `textForEmbedding` to the page content.
- **Vector databases**: connect the dataset to the Pinecone, Qdrant or other vector DB integrations in Apify Console, or call the Apify API from your code.
- **Schedules**: run it daily or weekly to keep your chatbot's knowledge fresh.

### FAQ

**Does it render JavaScript-heavy sites?** Yes. In Auto mode it first fetches each page over plain HTTP. If the page comes back nearly empty (a typical single-page app) or blocked (403/429), it opens the page in headless Chrome, waits for content, scrolls to load lazy content, and extracts the result. Links that only appear after rendering are followed too.

**Can it read scanned PDFs?** Yes. Pages without a text layer are rendered at 200 DPI and read with Tesseract OCR. Normal text pages in the same PDF are read directly, so mixed documents are handled correctly and you only pay OCR for the scanned pages. Each chunk's `pageStart`/`pageEnd` still points to the right page, and `ocrPages` on each record tells you how many pages needed OCR.

**Does it handle logins or CAPTCHAs?** No. It reads publicly accessible pages only.

**Is it legal to crawl websites?** The Actor respects robots.txt by default. Only crawl content you have the right to use, and check each site's terms.

**Found a bug or need a feature?** Open an issue on the Issues tab. Feedback shapes the roadmap.

# Actor input Schema

## `startUrls` (type: `array`):

Websites to crawl and/or direct links to PDF files. Each website is crawled within its own domain.

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

Maximum number of web pages / PDF files to process in total.

## `maxCrawlDepth` (type: `integer`):

How many links away from the start URLs to follow. 0 = only the start URLs.

## `outputMode` (type: `string`):

'chunks' gives ready-to-embed pieces (best for vector databases). 'documents' gives one clean Markdown record per page.

## `chunkSizeTokens` (type: `integer`):

Target size of each chunk, in approximate tokens (1 token ≈ 4 characters). 300-800 works well for most embedding models.

## `chunkOverlapTokens` (type: `integer`):

How much text consecutive chunks in the same section share, so answers that span a boundary are not lost.

## `addContextHeader` (type: `boolean`):

Fills 'textForEmbedding' with 'Page title > Section' before the chunk text. This usually improves retrieval quality.

## `minPageWords` (type: `integer`):

Pages with less text than this (login pages, empty listings) are skipped and not charged.

## `renderJavaScript` (type: `string`):

'Auto' (recommended) uses a real browser only for pages that come back empty or blocked without it, so simple sites stay fast and cheap. 'Always' renders every page in a browser. 'Never' is fastest.

## `renderIfFewerWordsThan` (type: `integer`):

Only used in Auto mode. If a page has fewer words than this over plain HTTP, it is re-opened in a real browser.

## `browserWaitSecs` (type: `integer`):

Time for late-loading content to appear.

## `maxBrowserPages` (type: `integer`):

How many pages the browser renders at the same time. More is faster but uses more memory.

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

'Auto' (recommended) reads only pages that have no text layer (scans, photos of documents). 'Always' OCRs every page. 'Off' skips OCR.

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

Languages in the scanned documents. Pick all that apply.

## `maxOcrPages` (type: `integer`):

Safety cap on scanned pages read per run.

## `saveTableImages` (type: `boolean`):

Each table found in a PDF is also saved as a PNG image. Chunks that contain the table link to it in 'tableImages', so people and multimodal AI models can see the original layout.

## `includeUrlGlobs` (type: `array`):

Optional glob patterns, e.g. https://example.com/docs/\*\*. Start URLs are always processed.

## `excludeUrlGlobs` (type: `array`):

Glob patterns to skip, e.g. **/tag/** or \**?page=*

## `sameDomainOnly` (type: `boolean`):

Only follow links that stay on the same website as the start URL.

## `stayUnderStartPath` (type: `boolean`):

Start at https://site.com/docs/guide and only that page and pages under /docs/guide/ are crawled. If the start URL is a file like /docs/intro.html, its folder /docs/ is used.

## `useSitemap` (type: `boolean`):

Discover pages from the site's sitemap as well as from links. Faster and more complete on most sites.

## `respectRobotsTxt` (type: `boolean`):

Skip pages the website asks crawlers not to visit in its robots.txt file.

## `keepLinks` (type: `boolean`):

Off by default: link URLs add noise for embeddings. Turn on to keep Markdown links.

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

How many pages are downloaded at the same time.

## `requestTimeoutSecs` (type: `integer`):

How long to wait for a page to load before giving up.

## `maxPdfSizeMb` (type: `integer`):

PDF files larger than this are skipped.

## Actor input object example

```json
{
  "startUrls": [
    {
      "url": "https://docs.apify.com/academy/web-scraping-for-beginners"
    }
  ],
  "maxPages": 100,
  "maxCrawlDepth": 3,
  "outputMode": "chunks",
  "chunkSizeTokens": 500,
  "chunkOverlapTokens": 50,
  "addContextHeader": true,
  "minPageWords": 30,
  "renderJavaScript": "auto",
  "renderIfFewerWordsThan": 60,
  "browserWaitSecs": 1,
  "maxBrowserPages": 2,
  "ocrMode": "auto",
  "ocrLanguages": [
    "eng"
  ],
  "maxOcrPages": 500,
  "saveTableImages": true,
  "sameDomainOnly": true,
  "stayUnderStartPath": false,
  "useSitemap": true,
  "respectRobotsTxt": true,
  "keepLinks": false,
  "maxConcurrency": 5,
  "requestTimeoutSecs": 30,
  "maxPdfSizeMb": 50
}
```

# Actor output Schema

## `chunks` (type: `string`):

All chunks (or documents in 'documents' mode) as JSON. Embed 'textForEmbedding', store 'text'.

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

Pages processed, skipped and failed, records output, JavaScript renders, OCR pages and table images.

# 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 = {
    "startUrls": [
        {
            "url": "https://docs.apify.com/academy/web-scraping-for-beginners"
        }
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("neighborly_ulexite/website-pdf-to-rag-chunks").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 = { "startUrls": [{ "url": "https://docs.apify.com/academy/web-scraping-for-beginners" }] }

# Run the Actor and wait for it to finish
run = client.actor("neighborly_ulexite/website-pdf-to-rag-chunks").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 '{
  "startUrls": [
    {
      "url": "https://docs.apify.com/academy/web-scraping-for-beginners"
    }
  ]
}' |
apify call neighborly_ulexite/website-pdf-to-rag-chunks --silent --output-dataset

```

## MCP server setup

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

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/gqWSKVLmiRmbbuJG8/builds/AlatGWEfE9MPy95oy/openapi.json
