Spain DNI (DNIe) OCR Python SDK

Instantly extract data and MRZ from Spanish IDs using our native Python library.

AI extracting data from a Spain ID card
StructOCR engine analyzing a Spanish document and MRZ lines in real-time.

Parsing DNI (DNIe) Challenges

Processing Spanish DNI cards poses unique challenges. Firstly, the text is primarily in Spanish, requiring models trained on this specific language. Secondly, DNI (DNIe) layout has evolved; the SDK must be able to handle both older and newer formats efficiently.

Why StructOCR for Spain

Our OCR model is specifically trained on a large dataset of Spanish DNI (DNIe) cards, ensuring high accuracy and reliability. The StructOCR Python SDK simplifies integration by providing a straightforward id parsing api for image processing and data extraction, fully supporting the Machine Readable Zone (MRZ) on the reverse side for strict global compliance. Focus on your application logic, not OCR complexities, while facilitating seamless kyc automation.

Common Use Cases in Spain

  • Digital Onboarding: Verify users for Fintech apps in Spain.
  • Telecom Registration: Automate SIM card registration with DNI (DNIe).
  • Hotel Check-in: Speed up guest registration workflows.

Live Demo: ID card scanner

No registration required. Upload a file to test the extraction.

1
Upload
2
Results

Drop files here or click to browse

JPG · PNG · WebP  ·  up to 500 files · max 4.5 MB each

No files selected
Need more testing? Create a free account to get 200 free credits (equals 100 National ID scans).

Python SDK Integration

Install the SDK via pip: `pip install structocr`. Then use the following code.

Prerequisite: Python 3.6+ and `structocr` library installed.

from structocr import StructOCR

# 💰 Save 30%+ vs competitors. Get 200 free credits instantly:
# 👉 https://structocr.com/register
# Initialize with your API Key
client = StructOCR("YOUR_API_KEY_HERE")

def scan_spain_id():
    # Note: Supports JPG, PNG, WebP (Max 4.5MB)
    # Target: DNI (DNIe)
    image_path = "spain_national_id.jpg"

    try:
        print(f"Scanning {image_path}...")
        
        # The SDK handles file upload and API communication
        # It automatically detects that this is a Spanish document
        result = client.scan_national_id(image_path)

        # Check success flag (SDK returns a dict matching the JSON response)
        if result.get('success'):
            data = result['data']
            print("✅ Spain Extraction Successful!")
            
            # Basic Identity
            print(f"Region:      {data.get('country_code')} (Series: {data.get('card_series')})")
            print(f"Name:        {data.get('given_names')} {data.get('surname')}")
            print(f"ID Number:   {data.get('document_number')}")
            
            # Critical Field: Personal Identity Number (CNP/CPF/NIN)
            print(f"Personal #:  {data.get('personal_number')}")
            
            # Demographics
            print(f"DOB:         {data.get('date_of_birth')} ({data.get('sex')})")
            print(f"Address:     {data.get('address')}")

            # Machine Readable Zone (MRZ)
            additional = data.get('additional_fields', {})
            if additional.get('mrz_line_1'):
                print("\n--- MRZ Data ---")
                print(additional.get('mrz_line_1'))
                print(additional.get('mrz_line_2'))
                if additional.get('mrz_line_3'):
                    print(additional.get('mrz_line_3'))
        else:
            print(f"❌ Extraction Failed: {result.get('error')}")

    except Exception as e:
        # Handle SDK or Network errors
        print(f"An error occurred: {e}")

if __name__ == "__main__":
    scan_spain_id()

Technical Specs

  • Latency: < 4s (Average)
  • Uptime: 99.9% SLA
  • Security: AES-256 Encryption & SOC2 Compliant
  • Input: JPG, PNG, WebP (Max 4.5MB)
  • Output: JSON (Structured Data)

Key Features

  • Native Script Support: Reads English and local characters.
  • MRZ Parsing: Accurately extracts and validates the Machine Readable Zone lines for cross-checking.
  • Blur Detection: Automatically rejects blurry images.
  • Fraud Check: Validates DNI (DNIe) number format.
  • Smart Crop: Removes background noise automatically.

JSON Response Example

The SDK returns a Python dictionary matching this JSON structure.

{
  "success": true,
  "data": {
    "type": "national_id",
    "country_code": "ESP",
    "nationality": "ESPAÑOLA",
    "document_number": "12345678Z",
    "card_series": "",
    "personal_number": "IDESP12345678Z",
    "surname": "GARCÍA",
    "given_names": "ANTONIO",
    "sex": "M",
    "date_of_birth": "1990-05-15",
    "place_of_birth": "MADRID",
    "address": "C/ Gran Vía 45, 3º Dcha, 28013 Madrid",
    "date_of_issue": "2020-01-01",
    "date_of_expiry": "2030-01-01",
    "issuing_authority": "Jefatura Superior de Policía",
    "additional_fields": {
      "phone_number": null,
      "tramite_number": null,
      "ejemplar": null,
      "mrz_line_1": "IDESP12345678Z<<<<<<<<<<<<<<<<",
      "mrz_line_2": "9005151M3001018ESP<<<<<<<<<<<4",
      "mrz_line_3": "GARCIA<<ANTONIO<<<<<<<<<<<<<<<"
    }
  }
}

Frequently Asked Questions

Does the Python SDK handle image uploads?

Yes, the SDK automatically handles base64 encoding and file uploads.

Is data stored?

No. Images are processed in-memory and deleted immediately.

How to handle errors?

The SDK result dictionary contains a 'success' boolean and an 'error' message if failed.

You May Also Like

Related tutorials, platform guides, and comparisons

Country Tutorial

Spain Passport OCR with Python SDK

Use the official StructOCR Python SDK and FastAPI to extract structured MRZ and VIZ data from Spain passports with a server-side integration.

Python · Passport
Country Tutorial

Tanzania Passport OCR with Python SDK

Use the official StructOCR Python SDK and FastAPI to extract structured MRZ and VIZ data from Tanzania passports with a server-side integration.

Python · Passport
Country Tutorial

Switzerland ID Card OCR Python SDK

Python Tutorial: Automate KYC in Switzerland. Extract data from the Swiss Identity Card (Identitätskarte) using StructOCR Python SDK. Supports multi-lingual text and MRZ extraction.

Python · swiss id
Country Tutorial

Uzbekistan Passport OCR with Python SDK

Use the official StructOCR Python SDK and FastAPI to extract structured MRZ and VIZ data from Uzbekistan passports with a server-side integration.

Python · Passport
Country Tutorial

Tajikistan ID Card (Karta) OCR Python SDK

Python Tutorial: Automate KYC in Tajikistan. Extract data from ID Card (Karta) using StructOCR Python SDK. Supports native text and MRZ extraction.

Python · id card (karta)
Country Tutorial

Ukraine Passport OCR with Python SDK

Use the official StructOCR Python SDK and FastAPI to extract structured MRZ and VIZ data from Ukraine passports with a server-side integration.

Python · Passport
Country Tutorial

Romania Carte de Identitate OCR Python SDK

Python Tutorial: Automate KYC in Romania. Extract data from Carte de Identitate using StructOCR Python SDK. Supports native text, front/back sides, and MRZ extraction.

Python · carte de identitate
Country Tutorial

Pakistan CNIC OCR Python SDK

Python Tutorial: Automate KYC in Pakistan. Extract data from CNIC using StructOCR Python SDK. Supports native text.

Python · cnic
Country Tutorial

Portugal Cartão de Cidadão OCR Python SDK

Python Tutorial: Automate KYC in Portugal. Extract data from Cartão de Cidadão using StructOCR Python SDK. Supports native text and MRZ extraction.

Python · cartão de cidadão
Country Tutorial

Philippines UMID OCR Python SDK

Python Tutorial: Automate KYC in Philippines. Extract data from UMID using StructOCR Python SDK. Supports native text.

Python · umid

Technical Comparisons & Integrations

Explore platform integrations and competitive analysis

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.

Instant Access Cancel Anytime 99.9% Uptime