# Pdf OCR API (`cspnair/pdf-ocr-api`) Actor

Extract and convert text from PDF documents using advanced optical character recognition technology with support for multiple AI models.

- **URL**: https://apify.com/cspnair/pdf-ocr-api.md
- **Developed by:** [csp](https://apify.com/cspnair) (community)
- **Categories:** AI, Developer tools, Other
- **Stats:** 77 total users, 6 monthly users, 100.0% runs succeeded, 6 bookmarks
- **User rating**: 5.00 out of 5 stars

## Pricing

from $0.01 / 1,000 results

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?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
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.
Actors are written with capital "A".

## 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.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## PDF OCR API - Multi-Model Text Extraction

Extract and convert text from PDF documents using advanced optical character recognition technology with support for multiple AI models.

### 🌟 Features

#### Multi-Model OCR Support

Choose from 8 different OCR engines based on your needs:

- **Google Vision API** - High accuracy commercial OCR with excellent language support
- **DeepSeek OCR** - Advanced AI-powered text extraction
- **Amazon Textract** - AWS-powered document analysis optimized for PDFs
- **Azure AI Vision** - Microsoft's computer vision OCR service
- **OpenAI GPT-4 Vision** - State-of-the-art multimodal AI for complex documents
- **Hugging Face** - Open-source transformer models for text extraction
- **Google Gemini** - Latest Google multimodal AI technology
- **Native (Tesseract.js)** - Free, no API key required, runs entirely in-container

#### Document Processing Features

- ✅ **Batch Processing** - Process multiple PDFs simultaneously
- ✅ **Multi-Language Support** - English, Spanish, French, German, Italian, Portuguese, Russian, Chinese, Japanese, Korean, Arabic, Danish
- ✅ **Structure Preservation** - Maintain document layout and formatting
- ✅ **Page Range Selection** - Process specific pages or page ranges
- ✅ **Multiple Output Formats** - JSON, Plain Text, or Markdown
- ✅ **High Resolution** - 300 DPI conversion for optimal OCR accuracy
- ✅ **Metadata Extraction** - Extract PDF metadata (title, author, dates)
- ✅ **Pay-Per-Page Pricing** - Fair billing based on actual pages processed (see [BILLING.md](./BILLING.md))

### 📋 Input Parameters

#### Required

- `ocrModel` - OCR model to use (default: "native")
- `pdfUrls` - Array of PDF document URLs to process

#### Optional

- `language` - Document language (default: "eng")
- `preserveFormatting` - Maintain document structure (default: true)
- `extractImages` - Extract images from PDF (default: false)
- `outputFormat` - Output format: "json", "text", or "markdown" (default: "json")
- `pageRange` - Pages to process: "all", "1-5", "1,3,5" (default: "all")

#### API Keys (model-specific)

- `googleVisionApiKey` - For Google Vision API
- `deepseekApiKey` - For DeepSeek OCR
- `awsAccessKeyId`, `awsSecretAccessKey`, `awsRegion` - For Amazon Textract
- `azureEndpoint`, `azureApiKey` - For Azure AI Vision
- `openaiApiKey` - For OpenAI GPT-4 Vision
- `huggingfaceApiKey` - For Hugging Face models
- `geminiApiKey` - For Google Gemini

### 🚀 Quick Start

#### Example Input (Native OCR - No API Key Required)

```json
{
  "ocrModel": "native",
  "pdfUrls": [
    "https://example.com/document.pdf"
  ],
  "language": "eng",
  "outputFormat": "json",
  "pageRange": "all"
}
```

#### Example with Google Vision API

```json
{
  "ocrModel": "google-vision",
  "googleVisionApiKey": "YOUR_API_KEY",
  "pdfUrls": [
    "https://example.com/document.pdf",
    "https://example.com/another-document.pdf"
  ],
  "language": "eng",
  "preserveFormatting": true,
  "outputFormat": "markdown"
}
```

#### Process Specific Pages

```json
{
  "ocrModel": "native",
  "pdfUrls": ["https://example.com/large-document.pdf"],
  "pageRange": "1-5,10,15-20",
  "outputFormat": "text"
}
```

### 📤 Output Format

#### JSON Output (default)

```json
{
  "pdfUrl": "https://example.com/document.pdf",
  "fileName": "document.pdf",
  "ocrModel": "native",
  "language": "eng",
  "success": true,
  "extractedAt": "2024-11-04T10:30:00.000Z",
  "pageCount": 5,
  "totalCharacters": 12450,
  "averageConfidence": 0.94,
  "pages": [
    {
      "pageNumber": 1,
      "text": "Page 1 content...",
      "confidence": 0.95,
      "width": 2480,
      "height": 3508
    }
  ],
  "fullText": "Complete document text..."
}
```

#### Text Output

```json
{
  "output": "Complete document text as plain string...",
  "pages": [
    {
      "pageNumber": 1,
      "text": "Page 1 content..."
    }
  ]
}
```

#### Markdown Output

```json
{
  "output": "# document.pdf\n\n**Pages:** 5\n\n## Page 1\n\nContent...",
  "pages": [
    {
      "pageNumber": 1,
      "markdown": "## Page 1\n\nContent..."
    }
  ]
}
```

### 💡 Use Cases

#### Business & Legal

- Contract analysis and digitization
- Legal document processing
- Invoice and receipt extraction
- Compliance document archiving

#### Academic & Research

- Research paper text extraction
- Academic document digitization
- Literature review automation
- Citation extraction

#### Content & Publishing

- Book digitization
- Magazine and newspaper archiving
- Historical document preservation
- Content migration projects

#### Development & Integration

- Document management systems
- Search and indexing pipelines
- Data extraction workflows
- Archive digitization projects

### 🔧 Supported Languages

- **English** (eng)
- **Spanish** (spa)
- **French** (fra)
- **German** (deu)
- **Italian** (ita)
- **Portuguese** (por)
- **Russian** (rus)
- **Chinese Simplified** (chi\_sim)
- **Japanese** (jpn)
- **Korean** (kor)
- **Arabic** (ara)

### 📊 Model Comparison

| Model | Speed | Accuracy | Cost | Best For |
|-------|-------|----------|------|----------|
| Native (Tesseract) | ⚡⚡⚡ | 85% | Free | Testing, simple docs |
| Google Vision | ⚡⚡ | 95% | $$ | Production, multi-language |
| Amazon Textract | ⚡⚡ | 96% | $$ | Forms, tables, structured docs |
| Azure Vision | ⚡⚡ | 94% | $$ | Enterprise integration |
| OpenAI GPT-4 | ⚡ | 94% | $$$ | Complex layouts, handwriting |
| Gemini | ⚡⚡ | 93% | $$ | Modern documents |

### 🎯 Best Practices

#### For Optimal Results

1. Use high-quality PDF sources (not scanned at low resolution)
2. Select the appropriate language setting
3. Use premium models for complex layouts or handwriting
4. Process pages in batches for large documents
5. Enable formatting preservation for structured documents

#### Performance Tips

1. Use page ranges to process only needed pages
2. Batch multiple PDFs in a single run
3. Choose Native OCR for simple, clear documents
4. Use premium models only when necessary

#### Cost Optimization

1. Start with Native OCR for testing
2. Use page ranges to avoid processing unnecessary pages
3. Batch process to reduce overhead
4. Monitor API costs for premium models

### 📈 Performance

- **Processing Speed**: 5-30 seconds per page (varies by model)
- **Concurrent Processing**: Up to 10 PDFs simultaneously
- **Maximum File Size**: 100MB per PDF
- **Supported Formats**: PDF (any version)
- **Resolution**: 300 DPI conversion

### 💰 Pricing

This actor uses pay-per-event pricing:

- **$0.01 per PDF** processed successfully (configurable)
- Failed PDFs are not charged
- Events tracked: `pdf_processed`

### 🆘 Support

For issues, questions, or feature requests:

- Check the [Apify documentation](https://docs.apify.com)
- Review the input schema for parameter details
- Ensure API keys are valid and have sufficient quota
- Verify PDF files are accessible and not corrupted

### 🔄 Version History

#### v1.0

- Initial release
- Support for 8 OCR models
- Multi-language support (12 languages)
- Batch processing capabilities
- Multiple output formats (JSON, Text, Markdown)
- Page range selection
- Structure preservation
- Pay-per-event pricing

### 📚 Related Actors

- **Receipt OCR API** - Specialized for receipt processing
- **Invoice OCR API** - Optimized for invoice extraction
- **Form OCR API** - Structured form data extraction

### 🔗 Links

- [Actor on Apify Store](https://apify.com/happitap/pdf-ocr-api)
- [Documentation](https://docs.apify.com)
- [Support](mailto:support@apify.com)

***

**Transform your PDF documents into searchable, structured data!** 📄✨

# Actor input Schema

## `ocrModel` (type: `string`):

Select the OCR model to use for text extraction

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

Array of PDF document URLs to process

## `language` (type: `string`):

Primary language of the documents

## `preserveFormatting` (type: `boolean`):

Maintain document layout and structure

## `extractImages` (type: `boolean`):

Extract and process images from PDF

## `outputFormat` (type: `string`):

Format for extracted text

## `pageRange` (type: `string`):

Specific pages to process (e.g., '1-5' or '1,3,5' or 'all')

## `googleVisionApiKey` (type: `string`):

Required if using Google Vision API

## `deepseekApiKey` (type: `string`):

Required if using DeepSeek OCR

## `awsAccessKeyId` (type: `string`):

Required if using Amazon Textract

## `awsSecretAccessKey` (type: `string`):

Required if using Amazon Textract

## `awsRegion` (type: `string`):

AWS region for Textract (e.g., us-east-1)

## `azureEndpoint` (type: `string`):

Required if using Azure AI Vision

## `azureApiKey` (type: `string`):

Required if using Azure AI Vision

## `openaiApiKey` (type: `string`):

Required if using OpenAI GPT-4 Vision

## `huggingfaceApiKey` (type: `string`):

Required if using Hugging Face models

## `geminiApiKey` (type: `string`):

Required if using Gemini API

## Actor input object example

```json
{
  "ocrModel": "native",
  "pdfUrls": [
    "https://pdfobject.com/pdf/sample.pdf"
  ],
  "language": "eng",
  "preserveFormatting": true,
  "extractImages": false,
  "outputFormat": "json",
  "pageRange": "all",
  "awsRegion": "us-east-1"
}
```

# Actor output Schema

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

Processing summary with total PDFs, success/failure counts, and pages processed

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

Full OCR extraction results for all processed PDFs

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

Quick overview of processed PDFs with key metrics

# 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://pdfobject.com/pdf/sample.pdf"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("cspnair/pdf-ocr-api").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://pdfobject.com/pdf/sample.pdf"] }

# Run the Actor and wait for it to finish
run = client.actor("cspnair/pdf-ocr-api").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://pdfobject.com/pdf/sample.pdf"
  ]
}' |
apify call cspnair/pdf-ocr-api --silent --output-dataset

```

## MCP server setup

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

```

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/Gc5TocCo6mQ8osLsj/builds/GszrQtHVXVxVFZrML/openapi.json
