OCR text extraction

OCR File
API Documentation

Extract text from PDFs and images with optical character recognition, create searchable PDFs, replace text, and convert scanned documents to editable Word files — over a simple REST API. Built for developers.

Try it now Back to API Hub

Overview

The OCR File API extracts text from PDF and image documents using pdfplumber and Tesseract OCR. It supports 11 languages, PDF and common image formats up to 50MB, and provides additional document-processing tools: replacing text in PDFs, creating searchable PDFs from scans, and converting extracted content into editable Word documents.

Base URL & Authentication

Base URL

Base URL

https://api.chemhub.com/api/v1

Authentication

Include your API credentials in every request header.

Headers

X-API-Key: your_api_key
X-API-Secret: your_secret
Content-Type: application/json

Get API Keys

Follow these steps to obtain your API credentials:

1

Log In to Your Account

Existing Users: Go to /login to access your dashboard

New Users: Visit /register to create your free account first

2

Access Your Profile

Once you log in, click on your profile picture in the top-right corner, then click on "Your profile" from the dropdown menu.

3

Create API Key

From your profile page, proceed to the "API Keys" section and create a key by filling in a name you prefer.

Example name

"Document OCR bot" or "My Archive Pipeline"

4

Save Your Credentials

Click on "Create API Key" to generate your credentials, then immediately copy and save both the API Key and Secret.

Critical Warning

Your secret key will only be displayed once! Copy it immediately and store it securely. You won't be able to see it again.

Security Notice

Never share your API keys publicly or commit them to version control. Treat them like passwords — regenerate immediately if compromised.

Rate Limits

8 requests per minute per API key. Check your dashboard for current usage and limits.

Endpoints

💚 Health CheckGET /ocr_file/health
📄 Extract TextPOST /ocr_file/extract_text
🖼️ OCR ImagePOST /ocr_file/ocr_image
✏️ Replace TextPOST /ocr_file/replace_text
🔎 Create Searchable PDFPOST /ocr_file/create_searchable
📝 Extract to WordPOST /ocr_file/extract_to_word

Health Check

GET/ocr_file/health

Health check endpoint to verify the OCR File service status, available backends, supported formats, and languages.

Response

Success Response

{
  "success": true,
  "status": "healthy",
  "ocr_file_available": true,
  "pdfplumber": true,
  "pdf2image": true,
  "pytesseract": true,
  "fpdf": true,
  "supported_formats": [".pdf", ".jpg", ".jpeg", ".png", ".bmp", ".tiff", ".tif"],
  "ocr_languages": ["eng", "spa", "fra", "deu", "ita", "por", "rus", "chi_sim", "chi_tra", "jpn", "kor"],
  "max_file_size_mb": 50,
  "timestamp": "2026-08-07T12:00:00"
}

Code Examples

Python

import requests

url = "https://api.chemhub.com/api/v1/ocr_file/health"

headers = {
    "X-API-Key": "your_api_key",
    "X-API-Secret": "your_secret"
}

res = requests.get(url, headers=headers)
print(res.json())

cURL

curl -X GET https://api.chemhub.com/api/v1/ocr_file/health \
-H "X-API-Key: your_api_key" \
-H "X-API-Secret: your_secret"

JavaScript

fetch('https://api.chemhub.com/api/v1/ocr_file/health', {
  method: 'GET',
  headers: {
    'X-API-Key': 'your_api_key',
    'X-API-Secret': 'your_secret'
  }
})
.then(res => res.json())
.then(console.log);

Extract Text from PDF or Image

POST/ocr_file/extract_text

Extract text from a PDF or image file. Enable OCR to capture text from scanned or image-based pages. Upload the file as multipart/form-data.

Form Parameters

FieldTypeDefaultDescription
fileFileDocument file (required) — PDF, JPG, JPEG, PNG, BMP, TIFF, or TIF, up to 50MB
use_ocrboolfalseSet to true to run OCR on scanned / image-based content
languagestringengOCR language — eng, spa, fra, deu, ita, por, rus, chi_sim, chi_tra, jpn, kor
dpiint300DPI used when rendering pages for OCR

Response

Success Response

{
  "success": true,
  "result": {
    "text": "Hello world. This is the extracted document content.",
    "page_count": 2,
    "characters": 87
  },
  "ocr_used": false,
  "language": "eng",
  "processing_time_ms": 245.13
}

cURL Example

cURL

curl -X POST "https://api.chemhub.com/api/v1/ocr_file/extract_text" \
  -H "X-API-Key: your_api_key" \
  -H "X-API-Secret: your_secret" \
  -F "file=@document.pdf" \
  -F "use_ocr=false" \
  -F "language=eng" \
  -F "dpi=300"

Code Examples

Python

import requests

url = "https://api.chemhub.com/api/v1/ocr_file/extract_text"

headers = {
    "X-API-Key": "your_api_key",
    "X-API-Secret": "your_secret"
}

with open("document.pdf", "rb") as f:
    files = {"file": f}
    data = {"use_ocr": "true", "language": "eng", "dpi": "300"}
    response = requests.post(url, headers=headers, files=files, data=data)

if response.status_code == 200:
    result = response.json()
    print("Extracted text:")
    print(result.get("result", {}).get("text"))
else:
    print(response.json())

JavaScript

const form = new FormData();
form.append('file', fileInput.files[0]);
form.append('use_ocr', 'true');
form.append('language', 'eng');
form.append('dpi', '300');

fetch('https://api.chemhub.com/api/v1/ocr_file/extract_text', {
  method: 'POST',
  headers: {
    'X-API-Key': 'your_api_key',
    'X-API-Secret': 'your_secret'
  },
  body: form
})
.then(res => res.json())
.then(data => console.log(data.result.text));

OCR Image

POST/ocr_file/ocr_image

Extract text from a single image file using Tesseract OCR. Upload the file as multipart/form-data.

Form Parameters

FieldTypeDefaultDescription
fileFileImage file (required) — JPG, JPEG, PNG, BMP, TIFF, or TIF, up to 50MB
languagestringengOCR language — eng, spa, fra, deu, ita, por, rus, chi_sim, chi_tra, jpn, kor

Response

Success Response

{
  "success": true,
  "result": "The text recognized from the image.",
  "language": "eng",
  "processing_time_ms": 412.87
}

cURL Example

cURL

curl -X POST "https://api.chemhub.com/api/v1/ocr_file/ocr_image" \
  -H "X-API-Key: your_api_key" \
  -H "X-API-Secret: your_secret" \
  -F "file=@scan.png" \
  -F "language=eng"

Replace Text in PDF

POST/ocr_file/replace_text

Replace occurrences of text inside a PDF and download the modified document. Upload the file as multipart/form-data with the replacements supplied as a JSON string.

Form Parameters

FieldTypeDescription
fileFilePDF file (required) — up to 50MB
replacementsstringJSON array of objects with find / replace pairs (required)

Replacements Example

replacements field

[
  {"find": "Acme Corp", "replace": "ChemHub"},
  {"find": "2025", "replace": "2026"}
]
Response

On success the endpoint returns the modified PDF as an attachment.

cURL Example

cURL

curl -X POST "https://api.chemhub.com/api/v1/ocr_file/replace_text" \
  -H "X-API-Key: your_api_key" \
  -H "X-API-Secret: your_secret" \
  -F "file=@document.pdf" \
  -F 'replacements=[{"find":"Acme Corp","replace":"ChemHub"}]' \
  --output replaced.pdf

Create Searchable PDF

POST/ocr_file/create_searchable

Convert a scanned PDF into a searchable PDF by running OCR and embedding a text layer. Upload the file as multipart/form-data.

Form Parameters

FieldTypeDefaultDescription
fileFilePDF file (required) — up to 50MB
languagestringengOCR language — eng, spa, fra, deu, ita, por, rus, chi_sim, chi_tra, jpn, kor
dpiint300DPI used when rendering pages for OCR
Response

On success the endpoint returns the searchable PDF as an attachment.

cURL Example

cURL

curl -X POST "https://api.chemhub.com/api/v1/ocr_file/create_searchable" \
  -H "X-API-Key: your_api_key" \
  -H "X-API-Secret: your_secret" \
  -F "file=@scanned.pdf" \
  -F "language=eng" \
  -F "dpi=300" \
  --output searchable.pdf

Extract to Word

POST/ocr_file/extract_to_word

Extract text from a document and convert it into a Microsoft Word (.docx) file. Upload the file as multipart/form-data. Generated documents are also available for download via GET /ocr_file/download_word_document/{filename}.

Form Parameters

FieldTypeDefaultDescription
fileFileDocument file (required) — PDF, JPG, JPEG, PNG, BMP, TIFF, TIF, or WEBP, up to 50MB
use_ocrbooltrueRun OCR on scanned / image-based content
languagestringengOCR language
dpiint300DPI used when rendering pages for OCR
enhance_handwritingboolfalseEnhance handwriting recognition

Response

Success Response

{
  "success": true,
  "result": "Word document generated successfully.",
  "processing_time_ms": 1204.55
}

cURL Example

cURL

curl -X POST "https://api.chemhub.com/api/v1/ocr_file/extract_to_word" \
  -H "X-API-Key: your_api_key" \
  -H "X-API-Secret: your_secret" \
  -F "file=@document.pdf" \
  -F "use_ocr=true" \
  -F "language=eng" \
  -F "dpi=300"

Python SDK

Complete Python SDK covering health check, text extraction, image OCR, text replacement, searchable PDF creation, and Word conversion.

Complete SDK Class

import requests
import json

BASE_URL = "https://api.chemhub.com/api/v1"
API_KEY = "YOUR_API_KEY"
API_SECRET = "YOUR_API_SECRET"

headers = {
    "X-API-Key": API_KEY,
    "X-API-Secret": API_SECRET
}

# --- Health Check ---
def check_health():
    return requests.get(f"{BASE_URL}/ocr_file/health", headers=headers).json()

# --- Extract text from a PDF or image ---
def extract_text(file_path, use_ocr=False, language="eng", dpi=300):
    with open(file_path, "rb") as f:
        files = {"file": f}
        data = {
            "use_ocr": "true" if use_ocr else "false",
            "language": language,
            "dpi": str(dpi)
        }
        response = requests.post(
            f"{BASE_URL}/ocr_file/extract_text",
            headers=headers,
            files=files,
            data=data
        )
    if response.status_code == 200:
        result = response.json()
        print(result.get("result", {}).get("text"))
        return result.get("result", {}).get("text")
    print(f"Error: {response.status_code} - {response.text}")
    return None

# --- OCR a single image ---
def ocr_image(file_path, language="eng"):
    with open(file_path, "rb") as f:
        files = {"file": f}
        data = {"language": language}
        response = requests.post(
            f"{BASE_URL}/ocr_file/ocr_image",
            headers=headers,
            files=files,
            data=data
        )
    if response.status_code == 200:
        return response.json().get("result")
    print(f"Error: {response.status_code} - {response.text}")
    return None

# --- Replace text in a PDF ---
def replace_text(file_path, replacements, output_path="replaced.pdf"):
    with open(file_path, "rb") as f:
        files = {"file": f}
        data = {"replacements": json.dumps(replacements)}
        response = requests.post(
            f"{BASE_URL}/ocr_file/replace_text",
            headers=headers,
            files=files,
            data=data
        )
    if response.status_code == 200:
        with open(output_path, "wb") as out:
            out.write(response.content)
        print(f"Saved: {output_path}")
        return output_path
    print(f"Error: {response.status_code} - {response.text}")
    return None

# --- Create a searchable PDF from a scan ---
def create_searchable(file_path, language="eng", dpi=300, output_path="searchable.pdf"):
    with open(file_path, "rb") as f:
        files = {"file": f}
        data = {"language": language, "dpi": str(dpi)}
        response = requests.post(
            f"{BASE_URL}/ocr_file/create_searchable",
            headers=headers,
            files=files,
            data=data
        )
    if response.status_code == 200:
        with open(output_path, "wb") as out:
            out.write(response.content)
        print(f"Saved: {output_path}")
        return output_path
    print(f"Error: {response.status_code} - {response.text}")
    return None

# --- Extract to Word ---
def extract_to_word(file_path, language="eng", dpi=300):
    with open(file_path, "rb") as f:
        files = {"file": f}
        data = {"use_ocr": "true", "language": language, "dpi": str(dpi)}
        response = requests.post(
            f"{BASE_URL}/ocr_file/extract_to_word",
            headers=headers,
            files=files,
            data=data
        )
    if response.status_code == 200:
        return response.json()
    print(f"Error: {response.status_code} - {response.text}")
    return None

# --- Test all endpoints ---
if __name__ == "__main__":
    print("=== OCR FILE API TEST ===")

    health = check_health()
    print(f"Health: {health.get('status', 'unknown')}")
    print(f"Languages: {health.get('ocr_languages', [])}")

    print("\n1. Extracting text from a PDF:")
    extract_text("document.pdf", use_ocr=True, language="eng")

    print("\n2. Replacing text in a PDF:")
    replace_text("document.pdf", [{"find": "Acme Corp", "replace": "ChemHub"}])

    print("\n3. Creating a searchable PDF:")
    create_searchable("scanned.pdf", language="eng")

Errors & Status Codes

Error Response Format

Error Response

{
  "success": false,
  "error": "Unsupported language",
  "message": "Unsupported language. Supported: eng, spa, fra, deu, ita, por, rus, chi_sim, chi_tra, jpn, kor"
}

Status Codes

CodeMeaning
200Success
400Bad request / no file / invalid format / unsupported language / invalid replacements
401Invalid or missing API key/secret
404Requested document file not found
413File too large (max 50MB)
429Rate limit exceeded
500Internal server error / processing failed
503Service unavailable / required backend library missing

Limitations

Maximum file size: 50MB
Rate limit: 8 requests per minute
Supported formats: PDF, JPG, JPEG, PNG, BMP, TIFF, TIF
Languages: eng, spa, fra, deu, ita, por, rus, chi_sim, chi_tra, jpn, kor
Backends: pdfplumber, pdf2image, pytesseract, fpdf
Processing time: OCR-heavy jobs on large files take longer