Why Tesseract & PyPDF2 Reverse Arabic RTL PDFs (and How to Extract Clean UTF-8 JSON)
Eliminate backwards Arabic strings, disconnected presentation glyphs, and mixed-script column drift with a single zero-retention vision OCR API.
Why PyPDF2, pdfminer, and Tesseract Break on Arabic & Bilingual PDFs
Engineering teams building GCC and MENA document pipelines almost always hit the same three failure modes when parsing Arabic PDFs with standard Python libraries. First, PDF text extractors like PyPDF2, pypdf, and pdfminer.six read glyphs in visual left-to-right painting order rather than logical Unicode order—turning a clean Arabic word like فاتورة into reversed characters (ةروتاف) or isolated Unicode Presentation Forms (U+FE70–U+FEFF). Patching that output with arabic-reshaper and python-bidi often corrupts embedded left-to-right tokens such as English SKU codes, IBANs, dates, and 15-digit VAT numbers. Second, running Tesseract with -l ara+eng on scanned bilingual statements, tax invoices, or stamped government forms frequently drops diacritics, splits cursive ligatures across columns, and outputs raw Eastern Arabic-Indic digits (٠١٢٣٤٥٦٧٨٩) that fail numeric parsing. Third, raw text dumps still leave you writing brittle regexes to pair Arabic labels with English equivalents and numerical totals.
Page-Level Vision Parsing to Clean UTF-8 JSON with POST /v1/pdf-extract
Instead of chaining Poppler, Tesseract language packs, and BiDi reversal hacks, send raw digital or scanned PDFs directly to StructOCR's Arabic OCR API via POST /v1/pdf-extract. Because StructOCR reads each page visually as a structured layout, logical right-to-left Arabic reading order stays intact alongside left-to-right English identifiers, Eastern Arabic-Indic numerals are normalized to standard Western digits (0-9), and you can enforce a custom JSON Schema (up to 50 fields) alongside stitched multi-page tables in a single call. Test the bilingual Arabic specimen interactively in the workbench below or in our free PDF to JSON converter. For Saudi ZATCA invoices, pair it with POST /v1/invoice or inspect TLV QR codes directly in our free ZATCA QR code scanner.
Where Teams Replace PyPDF2 & Tesseract on Arabic Documents
- Bilingual Arabic–English Tax Invoices & ZATCA Audits: Extract Arabic and English vendor names, 15-digit Saudi VAT (
3...3) or UAE TRN (100...) numbers, and line-item tables without BiDi reversal—or route directly to POST /v1/invoice for built-in ZATCA TLV QR cross-checking. - Scanned Contracts, Bank Statements & Government PDFs: Handle copier scans, phone-captured PDFs, and rubber stamps where
PyPDF2returns empty strings and Tesseract scrambles multi-column RTL blocks. - Strict Custom JSON Schemas for ERP & FinTech Ingestion: Pass a field array or JSON Schema in
mode=autoormode=jsonso downstream PostgreSQL, SAP, or ERPNext workers receive typed UTF-8 JSON rather than unstructured text. - Unified Regional ID, Vehicle & Health Card Pipelines: Pair general Arabic PDF extraction with dedicated StructOCR GCC endpoints for Saudi Istimara, UAE Mulkiya, KSA & UAE health cards, Emirates ID, and Saudi Iqama.
Python Implementation: Extract Clean UTF-8 JSON from an Arabic RTL PDF
Upload a scanned or digital Arabic–English PDF via multipart/form-data to POST https://api.structocr.com/v1/pdf-extract. Always write JSON output with ensure_ascii=False and encoding="utf-8" so Arabic strings stay human-readable instead of escaped \u0627 sequences. See full parameters in the PDF Extract API docs.
Prerequisite: Python 3.9+ (`pip install requests`; no Tesseract, Poppler, `arabic-reshaper`, or `python-bidi` required)
import json
import os
import requests
bilingual_schema = {
"type": "object",
"properties": {
"vendor_name_ar": {"type": "string", "description": "Vendor legal name in Arabic"},
"vendor_name_en": {"type": "string", "description": "Vendor legal name in English"},
"vat_number": {"type": "string", "description": "15-digit KSA VAT or UAE TRN in Western digits"},
"invoice_number": {"type": "string"},
"issue_date": {"type": "string", "description": "Gregorian YYYY-MM-DD"},
"currency": {"type": "string"},
"subtotal_amount": {"type": "number"},
"vat_amount": {"type": "number"},
"total_amount": {"type": "number"},
},
}
with open("bilingual_arabic_invoice.pdf", "rb") as pdf_file:
response = requests.post(
"https://api.structocr.com/v1/pdf-extract",
headers={"x-api-key": os.environ["STRUCTOCR_API_KEY"]},
files={"file": ("bilingual_arabic_invoice.pdf", pdf_file, "application/pdf")},
data={
"mode": "auto",
"pages": "all",
"stitch_tables": "true",
"schema": json.dumps(bilingual_schema),
},
timeout=90,
)
response.raise_for_status()
payload = response.json()
# Keep UTF-8 Arabic characters readable in logs and saved JSON files
with open("extracted_arabic.json", "w", encoding="utf-8") as out_file:
json.dump(payload["custom_data"], out_file, ensure_ascii=False, indent=2)
print("Vendor (AR):", payload["custom_data"]["vendor_name_ar"])
print("Vendor (EN):", payload["custom_data"]["vendor_name_en"])
print("Tables extracted:", len(payload["document"]["tables"]))Technical Specs
- •RTL & Mixed-Script Order: Reads logical Arabic UTF-8 alongside LTR English IDs, IBANs, and dates without `python-bidi` or `arabic-reshaper` post-processing
- •Numeral Normalization: Converts Eastern Arabic-Indic digits (`٠١٢٣٤٥٦٧٨٩`) to standard Western `0-9` numeric strings automatically
- •Digital & Scanned Inputs: Supports text PDFs, image-only scans, JPG, PNG, and WebP up to 10 MB and up to 20 pages per request
- •Structured Output Modes: `mode=json` (custom schema up to 50 fields), `mode=tables` (stitched tables), or `mode=auto` (both together)
- •Privacy: Strict Zero Data Retention on `POST /v1/pdf-extract` (in-memory processing; `raw_response: null`; zero model training)
- •Pricing: 2 credits per succeeded page; failed pages refund automatically; 200 permanent free credits on signup
Key Features
- •Zero RTL character-reversal bugs: Eliminates backwards Arabic output caused by PDF visual glyph ordering.
- •No Tesseract `ara.traineddata` tuning: Removes Poppler, ImageMagick, deskewing pipelines, and high-RAM OCR containers from your stack.
- •Deterministic schema + table output: Receive clean `custom_data` fields and `document.tables[]` in one HTTPS response.
- •Ready for GCC compliance workflows: Pair with `/v1/invoice` (`gcc_compliance` ZATCA TLV QR & VAT/TRN checks) and `/v1/national-id` (Emirates ID, Saudi Iqama, and Hijri conversion).
Example Bilingual Arabic–English JSON Response (Synthetic Specimen)
Synthetic `POST /v1/pdf-extract` (`mode=auto`) response showing intact logical UTF-8 Arabic strings, Western-normalized numbers, and structured line items.
{
"success": true,
"mode": "auto",
"document": {
"summary": {
"document_type": "tax_invoice",
"title": "فاتورة ضريبية / Bilingual Tax Invoice #INV-KSA-2026-0819 (Synthetic Sample)",
"language": "ar"
},
"fields": {
"vendor_name_ar": "شركة الأفق للتقنية المحدودة",
"vendor_name_en": "Al-Ufuq Technology Co. Ltd.",
"vendor_vat_number": "310482910400003",
"invoice_number": "INV-KSA-2026-0819",
"issue_date": "2026-11-18",
"currency": "SAR"
},
"tables": [
{
"id": "table_1",
"title": "بنود الفاتورة / Invoice Line Items",
"page_range": [
1,
1
],
"stitched": false,
"headers": [
"الوصف / Description",
"الكمية / Qty",
"سعر الوحدة / Unit Price (SAR)",
"ضريبة 15% / VAT",
"الإجمالي / Total (SAR)"
],
"rows": [
[
"رخصة منصة التحليل السحابي — Cloud Analytics Platform License",
"10",
"450.00",
"675.00",
"5,175.00"
],
[
"تكامل واجهة برمجة التطبيقات — Enterprise API Onboarding",
"1",
"2,800.00",
"420.00",
"3,220.00"
]
]
}
]
},
"custom_data": {
"vendor_name_ar": "شركة الأفق للتقنية المحدودة",
"vendor_name_en": "Al-Ufuq Technology Co. Ltd.",
"vat_number": "310482910400003",
"invoice_number": "INV-KSA-2026-0819",
"issue_date": "2026-11-18",
"currency": "SAR",
"subtotal_amount": 7300,
"vat_amount": 1095,
"total_amount": 8395
},
"pages": [
{
"page": 1,
"status": "ok",
"tables_found": 1
}
],
"usage": {
"page_count": 1,
"pages_processed": 1,
"pages_succeeded": 1,
"credits_per_page": 2,
"credits_charged": 2
}
}Frequently Asked Questions
Why does PyPDF2 reverse Arabic text even on digitally generated PDFs?
PDF generators store character drawing commands in visual left-to-right page order rather than logical Unicode reading order, and many embed Arabic letters as Presentation Form glyphs. Because PyPDF2 reads raw stream tokens without visual layout reconstruction, Arabic strings come out backwards and break mixed English/number sequences.
Do I still need arabic-reshaper or python-bidi with StructOCR?
No. StructOCR returns logical UTF-8 Arabic text ready for web UIs, PostgreSQL, JSON APIs, and Excel. In Python, simply serialize responses with ensure_ascii=False and write files using encoding="utf-8" (or utf-8-sig when generating CSV files for Microsoft Excel).
How does StructOCR handle Eastern Arabic-Indic numerals (٠١٢٣٤٥٦٧٨٩) and ZATCA QR codes?
Numeric values printed in Eastern Arabic-Indic digits (٠-٩) are normalized to standard Western digits (0-9). If you are processing Saudi or UAE VAT invoices and need deterministic 15-digit VAT/TRN validation plus ZATCA Phase 1/2 TLV QR cross-checking, use POST /v1/invoice or decode QR payloads locally with our ZATCA QR code scanner.
Is uploaded Arabic document data stored or used for AI training?
No. POST /v1/pdf-extract enforces strict zero data retention: uploaded PDFs are processed in memory only, never saved to storage buckets, never logged in usage_logs.raw_response, and never used to train models.
You May Also Like
Related tutorials, platform guides, and comparisons
Convert PDF to JSON in Python – Custom Schema & OCR API
Convert scanned and digital PDFs to structured JSON in Python using POST /v1/pdf-extract. Enforce custom JSON schemas, stitch multi-page tables, and upload 10 MB binary PDFs.
Camelot PDF Alternative for Borderless & Scanned Tables
Replace camelot-py without Ghostscript or OpenCV dependencies. Extract borderless, scanned, and multi-page PDF tables into Excel, CSV, and JSON via POST /v1/pdf-extract.
Tabula Alternative for Scanned & Multi-Page PDF Tables
Replace Tabula and tabula-py without Java/JVM dependencies. Extract scanned, borderless, and multi-page PDF tables into stitched CSV, Excel, and JSON via POST /v1/pdf-extract.
Convert PDF to JSON in Java – Scanned PDF & Schema OCR API
Convert scanned or digital PDFs into typed JSON in Java 17+ and Spring Boot via POST /v1/pdf-extract. Supports 10 MB multipart uploads, custom JSON schemas, and stitched tables.
Extract Table from PDF to CSV in Node.js – Scanned PDF Table API
Convert scanned and multi-page PDF tables into RFC-4180 UTF-8 CSV files in Node.js 18+ and TypeScript via POST /v1/pdf-extract without native binary dependencies.
Java National ID Parser API
Upload an image for a free test! Eliminate manual data entry for national IDs. Our Java ID card parsing API provides AES-256 encrypted JSON output in <4s average latency, ensuring SOC2 compliant verification.
Java Receipt OCR API
Tutorial: Integrate StructOCR's Receipt API into your Java enterprise applications. Upload an image for a free test! Extract line items, merchants, and taxes from POS receipts into structured JSON.
Java Passport OCR API
Extract passport MRZ and VIZ data in Java. Upload an image for a free test! Our API provides structured JSON output, handling glare and blur automatically.
Java Weighbridge Ticket OCR API Tutorial
Integrate a weighbridge ticket OCR API in Java. Extract ticket, vehicle, material, gross, tare, net, and review signals from images or PDFs.
Arizona Driver License & ID Card PDF417 API
Decode the PDF417 barcode on Arizona driver licenses and state ID cards into AAMVA JSON, with document_kind to tell licenses from ID cards.
Arabic PDF Table to Excel – RTL & Numerals Guide
Extract bilingual Arabic-English PDF tables to Excel (.xlsx) and UTF-8 BOM CSV without scrambled RTL columns, broken Eastern numerals (٠-٩), or duplicate multi-page headers.
Technical Comparisons & Integrations
Explore platform integrations and competitive analysis
Add Receipt OCR to Your Lovable.dev App in 5 Minutes
Step-by-step guide to integrating the StructOCR receipt API into a Lovable.dev app. No backend required — just paste a prompt and add your API key.
Add VIN OCR to Your Lovable.dev App in 5 Minutes
Step-by-step guide to integrating the StructOCR VIN scanner API into a Lovable.dev app. Build automotive and fleet tools with zero backend required.
Manual TOS Entry vs. Container OCR Automation API
Analyzing the ROI and operational efficiency of replacing manual gate checkers with an automated Container OCR API in logistics yards.
Saudi Driving Licence OCR in n8n: Licences to JSON
Read Saudi driving licences in n8n with one HTTP Request node: licence and ID number, name, dates and licence class as JSON. Includes a ready-made workflow to import.
Saudi Istimara OCR in n8n: Registration Cards to JSON
Build an n8n workflow that reads Saudi vehicle registration cards (Istimara) with one HTTP Request node: owner and user IDs, plate, VIN, vehicle weight, load capacity and sequence number as JSON.
Saudi National ID & Iqama OCR in n8n: KYC to JSON
Read Saudi National IDs and Iqamas in n8n with one HTTP Request node: 10-digit ID number, name, nationality, dates and MRZ as JSON. Includes a ready-made workflow to import.
From tutorial to production in 5 minutes.
You've seen the code. Now get your API key, grab your 200 free credits, and see it work with your own images. No credit card required.