# Fast Pdf Processor (`contemporary_fruit/pdf-processor-actor`) Actor

This API is a PDF Processing Service allowing users to upload a PDF to:

Extract Text: Reads all text from the PDF and returns it as structured JSON data per page.
Merge Pages: Creates a new PDF containing only the specific pages selected by the user. (260 characters)

- **URL**: https://apify.com/contemporary_fruit/pdf-processor-actor.md
- **Developed by:** [Andric](https://apify.com/contemporary_fruit) (community)
- **Categories:** Developer tools, Automation, Other
- **Security:** Limited permissions
- **Stats:** 2 total users, 0 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-usage

## 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 Processor - Apify Actor Deployment Guide

### Overview

This PDF Processor provides four main operations via Apify Actor:

1. **Extract Text** - Extract text content from all PDF pages
2. **Merge Pages** - Create new PDFs with selected pages only
3. **HTML to PDF** - Convert HTML content to PDF using Playwright
4. **URL to PDF** - Convert web pages to PDF using Playwright

### Files Structure

```
pdf-processor-actor/
├── main.py                    # Apify Actor wrapper (main entry point)
├── requirements.txt           # Dependencies for Apify deployment
├── requirements_apify.txt     # Alternative requirements file
├── Dockerfile                 # Docker configuration for Apify
├── actor.json                 # Apify Actor configuration
├── INPUT_SCHEMA.json          # Input schema definition
├── apify_input_schema.json   # Legacy input schema
├── apify_output_schema.json  # Output schema definition
├── sample_inputs.json         # Example inputs for testing
├── test_local.py              # Local testing script
├── n8n_workflow_example.json  # n8n integration example
├── n8n_direct_api_workflow.json # n8n direct API workflow
├── QUICK_START.md            # Quick start guide
├── apify.json                # Apify configuration
├── actor/                    # Actor configuration directory
│   ├── actor.json
│   └── dataset_schema.json
└── README.md                  # This file
```

### Deployment Steps

#### 1. Prepare Your Repository

```bash
## Create a new directory for your actor
mkdir pdf-processor-actor
cd pdf-processor-actor

## Copy all the provided files
cp /path/to/main.py .
cp /path/to/app.py .
cp /path/to/requirements_apify.txt .
cp /path/to/Dockerfile .
cp /path/to/actor.json .
cp /path/to/apify_input_schema.json .
cp /path/to/apify_output_schema.json .
cp /path/to/sample_inputs.json .
```

#### 2. Deploy to Apify

##### Option A: Using Apify CLI

```bash
## Install Apify CLI
npm install -g apify-cli

## Login to your Apify account
apify login

## Initialize the actor
apify init

## Push to Apify platform
apify push
```

##### Option B: Using GitHub Integration

1. Push your code to a GitHub repository
2. Go to [Apify Console](https://console.apify.com)
3. Click "Actors" → "Create new"
4. Choose "From GitHub repository"
5. Connect your GitHub repo
6. Apify will automatically build and deploy

#### 3. Configure the Actor

In Apify Console:

1. Navigate to your actor
2. Go to "Settings" tab
3. Set the following:
   - **Build tag**: `latest`
   - **Memory**: `512 MB` (minimum, increase for complex webpages or large PDFs)
   - **Timeout**: `300 seconds` (adjust based on PDF size and webpage complexity)

#### 4. Test Your Actor

1. Go to the "Input" tab
2. Use one of the sample inputs:

**Extract Text:**

```json
{
  "action": "extract-text",
  "pdfUrl": "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
}
```

**Merge Pages:**

```json
{
  "action": "merge-pages",
  "pdfUrl": "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
  "pageNumbers": [0, 2, 4]
}
```

**HTML to PDF:**

```json
{
  "action": "html-to-pdf",
  "html": "<html><body><h1>Hello World</h1><p>This is a test PDF.</p></body></html>"
}
```

**URL to PDF:**

```json
{
  "action": "url-to-pdf",
  "pdfUrl": "https://example.com"
}
```

3. Click "Run"
4. Check the output in the "Dataset" tab

### Usage Examples

#### Via Apify API

```python
from apify_client import ApifyClient

client = ApifyClient('YOUR_API_TOKEN')
actor = client.actor('YOUR_USERNAME/pdf-processor')

## Extract text
run = actor.call(run_input={
    "action": "extract-text",
    "pdfUrl": "https://example.com/document.pdf"
})

## HTML to PDF
run = actor.call(run_input={
    "action": "html-to-pdf",
    "html": "<html><body><h1>Invoice</h1><p>Amount: $100</p></body></html>"
})

## URL to PDF
run = actor.call(run_input={
    "action": "url-to-pdf",
    "pdfUrl": "https://example.com"
})

## Get results
dataset = client.dataset(run['defaultDatasetId'])
results = list(dataset.iterate_items())
```

#### Via REST API

```bash
## Extract text
curl -X POST https://api.apify.com/v2/acts/YOUR_USERNAME~pdf-processor/runs \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -d '{
    "action": "extract-text",
    "pdfUrl": "https://example.com/document.pdf"
  }'

## HTML to PDF
curl -X POST https://api.apify.com/v2/acts/YOUR_USERNAME~pdf-processor/runs \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -d '{
    "action": "html-to-pdf",
    "html": "<html><body><h1>Invoice</h1></body></html>"
  }'

## URL to PDF
curl -X POST https://api.apify.com/v2/acts/YOUR_USERNAME~pdf-processor/runs \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -d '{
    "action": "url-to-pdf", 
    "pdfUrl": "https://example.com"
  }'
```

### Monitoring

- Check logs in the "Runs" tab for debugging
- Monitor performance in the "Analytics" tab
- Set up webhooks for run completion notifications

### Cost Estimation

- **Compute Units**:
  - Text extraction: ~0.001 CU per page
  - Page merging: ~0.002 CU per page
  - HTML/URL to PDF: ~0.005-0.02 CU (depends on complexity and load time)
- **Storage**: Minimal for text, ~1 MB per 100 pages for generated PDFs
- **Bandwidth**: Depends on PDF/webpage size (input + output)

### Limitations

- Maximum PDF size: 100 MB (configurable)
- Maximum pages to process: 1000 (configurable)
- Timeout: 5 minutes default (configurable)
- HTML/URL to PDF: Requires Playwright/Chrome (included in Docker image)
- Complex JavaScript sites may need additional wait time

### Support

For issues or questions:

1. Check the actor logs for error details
2. Verify PDF URL is publicly accessible
3. Ensure page numbers are within valid range

### License

MIT

# Actor input Schema

## `action` (type: `string`):

Choose which operation to perform.

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

Direct URL to a PDF (for extraction/merge) OR a Website URL (for url-to-pdf).

## `html` (type: `string`):

Raw HTML string to convert to PDF. (Required only for html-to-pdf action)

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

Base64-encoded PDF data (alternative to pdfUrl for binary uploads).

## `pageNumbers` (type: `array`):

List of page indices (0-based) to extract and merge.

## `saveToKeyValueStore` (type: `boolean`):

Whether to save the output PDF to Apify's Key-Value Store (generates download URL).

## Actor input object example

```json
{
  "action": "extract-text",
  "pdfUrl": "https://raw.githubusercontent.com/mozilla/pdf.js/master/web/compressed.tracemonkey-pldi-09.pdf",
  "pageNumbers": [
    0,
    1
  ],
  "saveToKeyValueStore": true
}
```

# 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://raw.githubusercontent.com/mozilla/pdf.js/master/web/compressed.tracemonkey-pldi-09.pdf"
};

// Run the Actor and wait for it to finish
const run = await client.actor("contemporary_fruit/pdf-processor-actor").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://raw.githubusercontent.com/mozilla/pdf.js/master/web/compressed.tracemonkey-pldi-09.pdf" }

# Run the Actor and wait for it to finish
run = client.actor("contemporary_fruit/pdf-processor-actor").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://raw.githubusercontent.com/mozilla/pdf.js/master/web/compressed.tracemonkey-pldi-09.pdf"
}' |
apify call contemporary_fruit/pdf-processor-actor --silent --output-dataset

```

## MCP server setup

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

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/ONCWv1A2lDslCrvU8/builds/keC9OrZ2NCsCffZrt/openapi.json
