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

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:** 1 total users, 0 monthly users, 100.0% runs succeeded, NaN bookmarks
- **User rating**: 5.00 out of 5 stars

## Pricing

Pay per event

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/platform/actors/running/actors-in-store#pay-per-event

# 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
- ✅ **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 (11 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",
  "language": "eng",
  "preserveFormatting": true,
  "extractImages": false,
  "outputFormat": "json",
  "pageRange": "all",
  "awsRegion": "us-east-1"
}
```

# 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 = {};

// 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 = {}

# 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("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call cspnair/pdf-ocr-api --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=cspnair/pdf-ocr-api",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

```json
{
    "openapi": "3.0.1",
    "info": {
        "title": "Pdf OCR API",
        "description": "Extract and convert text from PDF documents using advanced optical character recognition technology with support for multiple AI models.",
        "version": "0.0",
        "x-build-id": "6iAdiOemDzPMyKPAf"
    },
    "servers": [
        {
            "url": "https://api.apify.com/v2"
        }
    ],
    "paths": {
        "/acts/cspnair~pdf-ocr-api/run-sync-get-dataset-items": {
            "post": {
                "operationId": "run-sync-get-dataset-items-cspnair-pdf-ocr-api",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for its completion, and returns Actor's dataset items in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        },
        "/acts/cspnair~pdf-ocr-api/runs": {
            "post": {
                "operationId": "runs-sync-cspnair-pdf-ocr-api",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor and returns information about the initiated run in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK",
                        "content": {
                            "application/json": {
                                "schema": {
                                    "$ref": "#/components/schemas/runsResponseSchema"
                                }
                            }
                        }
                    }
                }
            }
        },
        "/acts/cspnair~pdf-ocr-api/run-sync": {
            "post": {
                "operationId": "run-sync-cspnair-pdf-ocr-api",
                "x-openai-isConsequential": false,
                "summary": "Executes an Actor, waits for completion, and returns the OUTPUT from Key-value store in response.",
                "tags": [
                    "Run Actor"
                ],
                "requestBody": {
                    "required": true,
                    "content": {
                        "application/json": {
                            "schema": {
                                "$ref": "#/components/schemas/inputSchema"
                            }
                        }
                    }
                },
                "parameters": [
                    {
                        "name": "token",
                        "in": "query",
                        "required": true,
                        "schema": {
                            "type": "string"
                        },
                        "description": "Enter your Apify token here"
                    }
                ],
                "responses": {
                    "200": {
                        "description": "OK"
                    }
                }
            }
        }
    },
    "components": {
        "schemas": {
            "inputSchema": {
                "type": "object",
                "required": [
                    "ocrModel",
                    "pdfUrls"
                ],
                "properties": {
                    "ocrModel": {
                        "title": "OCR Model",
                        "enum": [
                            "google-vision",
                            "deepseek-ocr",
                            "amazon-textract",
                            "azure-vision",
                            "openai",
                            "huggingface",
                            "gemini",
                            "native"
                        ],
                        "type": "string",
                        "description": "Select the OCR model to use for text extraction",
                        "default": "native"
                    },
                    "pdfUrls": {
                        "title": "PDF Document URLs",
                        "minItems": 1,
                        "type": "array",
                        "description": "Array of PDF document URLs to process",
                        "items": {
                            "type": "string"
                        }
                    },
                    "language": {
                        "title": "Document Language",
                        "enum": [
                            "eng",
                            "spa",
                            "fra",
                            "deu",
                            "ita",
                            "por",
                            "rus",
                            "chi_sim",
                            "jpn",
                            "kor",
                            "ara"
                        ],
                        "type": "string",
                        "description": "Primary language of the documents",
                        "default": "eng"
                    },
                    "preserveFormatting": {
                        "title": "Preserve Document Formatting",
                        "type": "boolean",
                        "description": "Maintain document layout and structure",
                        "default": true
                    },
                    "extractImages": {
                        "title": "Extract Images",
                        "type": "boolean",
                        "description": "Extract and process images from PDF",
                        "default": false
                    },
                    "outputFormat": {
                        "title": "Output Format",
                        "enum": [
                            "json",
                            "text",
                            "markdown"
                        ],
                        "type": "string",
                        "description": "Format for extracted text",
                        "default": "json"
                    },
                    "pageRange": {
                        "title": "Page Range",
                        "type": "string",
                        "description": "Specific pages to process (e.g., '1-5' or '1,3,5' or 'all')",
                        "default": "all"
                    },
                    "googleVisionApiKey": {
                        "title": "Google Vision API Key",
                        "type": "string",
                        "description": "Required if using Google Vision API"
                    },
                    "deepseekApiKey": {
                        "title": "DeepSeek API Key",
                        "type": "string",
                        "description": "Required if using DeepSeek OCR"
                    },
                    "awsAccessKeyId": {
                        "title": "AWS Access Key ID",
                        "type": "string",
                        "description": "Required if using Amazon Textract"
                    },
                    "awsSecretAccessKey": {
                        "title": "AWS Secret Access Key",
                        "type": "string",
                        "description": "Required if using Amazon Textract"
                    },
                    "awsRegion": {
                        "title": "AWS Region",
                        "type": "string",
                        "description": "AWS region for Textract (e.g., us-east-1)",
                        "default": "us-east-1"
                    },
                    "azureEndpoint": {
                        "title": "Azure Vision Endpoint",
                        "type": "string",
                        "description": "Required if using Azure AI Vision"
                    },
                    "azureApiKey": {
                        "title": "Azure Vision API Key",
                        "type": "string",
                        "description": "Required if using Azure AI Vision"
                    },
                    "openaiApiKey": {
                        "title": "OpenAI API Key",
                        "type": "string",
                        "description": "Required if using OpenAI GPT-4 Vision"
                    },
                    "huggingfaceApiKey": {
                        "title": "Hugging Face API Key",
                        "type": "string",
                        "description": "Required if using Hugging Face models"
                    },
                    "geminiApiKey": {
                        "title": "Google Gemini API Key",
                        "type": "string",
                        "description": "Required if using Gemini API"
                    }
                }
            },
            "runsResponseSchema": {
                "type": "object",
                "properties": {
                    "data": {
                        "type": "object",
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "actId": {
                                "type": "string"
                            },
                            "userId": {
                                "type": "string"
                            },
                            "startedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "finishedAt": {
                                "type": "string",
                                "format": "date-time",
                                "example": "2025-01-08T00:00:00.000Z"
                            },
                            "status": {
                                "type": "string",
                                "example": "READY"
                            },
                            "meta": {
                                "type": "object",
                                "properties": {
                                    "origin": {
                                        "type": "string",
                                        "example": "API"
                                    },
                                    "userAgent": {
                                        "type": "string"
                                    }
                                }
                            },
                            "stats": {
                                "type": "object",
                                "properties": {
                                    "inputBodyLen": {
                                        "type": "integer",
                                        "example": 2000
                                    },
                                    "rebootCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "restartCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "resurrectCount": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "computeUnits": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "options": {
                                "type": "object",
                                "properties": {
                                    "build": {
                                        "type": "string",
                                        "example": "latest"
                                    },
                                    "timeoutSecs": {
                                        "type": "integer",
                                        "example": 300
                                    },
                                    "memoryMbytes": {
                                        "type": "integer",
                                        "example": 1024
                                    },
                                    "diskMbytes": {
                                        "type": "integer",
                                        "example": 2048
                                    }
                                }
                            },
                            "buildId": {
                                "type": "string"
                            },
                            "defaultKeyValueStoreId": {
                                "type": "string"
                            },
                            "defaultDatasetId": {
                                "type": "string"
                            },
                            "defaultRequestQueueId": {
                                "type": "string"
                            },
                            "buildNumber": {
                                "type": "string",
                                "example": "1.0.0"
                            },
                            "containerUrl": {
                                "type": "string"
                            },
                            "usage": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "integer",
                                        "example": 1
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            },
                            "usageTotalUsd": {
                                "type": "number",
                                "example": 0.00005
                            },
                            "usageUsd": {
                                "type": "object",
                                "properties": {
                                    "ACTOR_COMPUTE_UNITS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATASET_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "KEY_VALUE_STORE_WRITES": {
                                        "type": "number",
                                        "example": 0.00005
                                    },
                                    "KEY_VALUE_STORE_LISTS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_READS": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "REQUEST_QUEUE_WRITES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_INTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "DATA_TRANSFER_EXTERNAL_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_RESIDENTIAL_TRANSFER_GBYTES": {
                                        "type": "integer",
                                        "example": 0
                                    },
                                    "PROXY_SERPS": {
                                        "type": "integer",
                                        "example": 0
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
```
