> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.sofer.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.sofer.ai/_mcp/server.

# Extract text with OCR

Standard, Enhanced, and Handwriting OCR turn a scanned PDF or image into HTML, one page at a time.
Authenticate with your personal API key using `Authorization: Bearer YOUR_API_KEY`.

## Price and limits

Choose a `mode` for each upload; omitting it defaults to `standard`.

| Mode          | API price per successful page | Equivalent purchased credits |
| ------------- | ----------------------------- | ---------------------------- |
| `standard`    | \$0.025                       | 1                            |
| `enhanced`    | \$0.125                       | 5                            |
| `handwriting` | \$0.25                        | 10                           |

Prices match purchased Document AI credits at \$2.50 per 100 credits. API requests draw
from your API dollar balance. Your website plan's included and purchased
Document AI credits are separate.

The API reserves the estimated charge before starting. For example, a 10-page Standard PDF
reserves $0.25. If only eight pages succeed, the final charge is $0.20 and the
unused \$0.05 reservation is released. A failure with no extracted pages releases
the whole reservation.

Upload a file of up to **20 MB before base64 encoding**. PDFs are counted
server-side; each image counts as one page. Supported types are PDF, PNG, JPEG,
WebP, BMP, GIF, and TIFF. Multi-frame images are treated as a single image;
convert them to PDF to process every page. Password-protected PDFs are unsupported.
Enhanced adds independent transcription and alignment for printed pages. Handwriting
transcribes handwritten pages and does not include image-to-text highlighting.

## Submit and poll

The following Python example uses the HTTP API and works without an SDK update.
Set `SOFERAI_API_KEY` in your environment, then run it with a local PDF or image.

```python
import base64
import mimetypes
import os
import time
from pathlib import Path

import httpx

source = Path("scan.pdf")
with httpx.Client(
    base_url="https://api.sofer.ai/v1/",
    headers={"Authorization": f"Bearer {os.environ['SOFERAI_API_KEY']}"},
    timeout=120,
) as client:
    response = client.post(
        "ocr/",
        json={
            "mode": "standard",  # Or "enhanced" or "handwriting".
            "file": base64.b64encode(source.read_bytes()).decode("ascii"),
            "file_name": source.name,
            "content_type": mimetypes.guess_type(source.name)[0] or "application/pdf",
            "title": "Scanned document",
        },
    )
    response.raise_for_status()
    created = response.json()
    document_id = created["document_id"]
    print("Reserved charge in cents:", created["estimated_api_cost_cents"])

    # Stop polling after ten minutes. A timeout does not cancel the OCR job.
    deadline = time.monotonic() + 600
    while time.monotonic() < deadline:
        response = client.get(f"ocr/{document_id}")
        response.raise_for_status()
        result = response.json()
        print(result["status"], result["completed_pages"], result["failed_pages"])
        if result["status"] in {"COMPLETED", "FAILED"}:
            break
        time.sleep(2)
    else:
        raise TimeoutError(f"Poll GET /v1/ocr/{document_id} again later")

    for page in result["pages"]:
        Path(f"page-{page['page_num']}.html").write_text(
            page["content"] or "", encoding="utf-8"
        )
    if result["status"] == "FAILED":
        print(result.get("error") or "Some pages could not be extracted")
```

`POST /v1/ocr/` returns `document_id`, initial `status`, `num_pages`, and
`estimated_api_cost_cents`. A value of `2.5` means \$0.025.

`GET /v1/ocr/{document_id}` returns `PENDING`, `PROCESSING`, `COMPLETED`, or
`FAILED`, along with page counts, a failure reason when available, and the HTML
already extracted. A failed job can still have successfully extracted pages.
Save your document ID and resume polling it after a connection failure. Submitting
the file again creates another document and another charge.

The same document ID works with the Documents API to retrieve, rename, move, or
translate your document. Supply an owned `folder_id` at creation to place it in a
folder. Translation is a separate billable operation.

## Errors

| HTTP status | Meaning                                                            |
| ----------- | ------------------------------------------------------------------ |
| 400         | Invalid base64, unsupported image/PDF, or encrypted PDF.           |
| 401         | Missing or invalid API key.                                        |
| 402         | Insufficient API balance; no OCR job starts.                       |
| 404         | Document or folder not found in your account.                      |
| 413         | File exceeds 20 MB.                                                |
| 422         | Invalid mode or request fields.                                    |
| 503         | Pricing for the selected OCR mode is not configured on the server. |