PHP code example of mayaram / laravel-ocr

1. Go to this page and download the library: Download mayaram/laravel-ocr library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mayaram / laravel-ocr example snippets


use Mayaram\LaravelOcr\Facades\LaravelOcr;

// Extract from a local file path
$result = LaravelOcr::extract('/path/to/document.png');
echo $result['text'];
// "INVOICE #1001..."

// Extract from an UploadedFile
$result = LaravelOcr::extract(request()->file('document'));

// Extract a table
$tableResult = LaravelOcr::extractTable('/path/to/invoice.png');
foreach ($tableResult['table'] as $row) {
    echo implode(' | ', $row) . "\n";
}

use Mayaram\LaravelOcr\DTOs\OcrResult;

/** @var \Mayaram\LaravelOcr\Services\DocumentParser $parser */
$parser = app('laravel-ocr.parser');

$result = $parser->parse('storage/invoices/inv-2024.pdf', [
    'document_type' => 'invoice',
    'use_ai_cleanup' => true,
    'save_to_database' => true,
]);

// Access the OcrResult DTO properties
echo $result->text;                                  // Full extracted text
echo $result->confidence;                            // e.g., 0.98
echo $result->metadata['processing_time'];           // e.g., 1.2
echo $result->metadata['document_type'];             // "invoice"
echo $result->metadata['ai_cleanup_used'];           // true

// Access structured fields
$fields = $result->metadata['fields'];
$invoiceNumber = $fields['invoice_number']['value'];
$totalAmount = $fields['totals']['total']['amount'];

$parser = app('laravel-ocr.parser');

$results = $parser->parseBatch([
    'storage/invoices/inv-001.pdf',
    'storage/invoices/inv-002.pdf',
    'storage/invoices/inv-003.pdf',
], ['document_type' => 'invoice']);

foreach ($results as $result) {
    echo $result->text . "\n---\n";
}

$result = $parser->parse($invoicePath, [
    'document_type' => 'invoice',
]);

// Line items are extracted automatically for invoices
$lineItems = $result->metadata['fields']['line_items'] ?? [];

foreach ($lineItems as $item) {
    echo "{$item['description']}: {$item['quantity']} x \${$item['unit_price']} = \${$item['total']}\n";
}
// Output:
// Web Hosting: 12 x $10.00 = $120.00
// Domain Name: 1 x $15.00 = $15.00

// Invoice totals
$totals = $result->metadata['fields']['totals'] ?? [];
echo "Subtotal: " . ($totals['subtotal']['formatted'] ?? 'N/A');
echo "Tax: " . ($totals['tax']['formatted'] ?? 'N/A');
echo "Total: " . ($totals['total']['formatted'] ?? 'N/A');

use Mayaram\LaravelOcr\Facades\LaravelOcr;

// 1. Create a Template
$templateManager = app('laravel-ocr.templates');

$template = $templateManager->create([
    'name' => 'TechCorp Invoice',
    'type' => 'invoice',
    'description' => 'Template for TechCorp invoices',
    'fields' => [
        [
            'key' => 'order_id',
            'label' => 'Order ID',
            'pattern' => '/Order\s*ID:\s*([A-F0-9]+)/i',
            'type' => 'string',
            'validators' => ['port templates
$json = $templateManager->exportTemplate($template->id);
$imported = $templateManager->importTemplate('/path/to/template.json');

// 5. Duplicate a template
$clone = $template->duplicate('TechCorp Invoice v2');

// config/laravel-ocr.php
'workflows' => [
    'invoice' => [
        'options' => [
            'use_ai_cleanup' => true,
            'auto_detect_template' => true,
            'extract_tables' => true,
        ],
        'post_processors' => [
            ['class' => 'App\OCR\Processors\InvoiceProcessor'],
        ],
        'validators' => [
            ['type' => '

// Usage
$parser = app('laravel-ocr.parser');
$result = $parser->parseWithWorkflow($file, 'invoice');

use Mayaram\LaravelOcr\Facades\LaravelOcr;

// Use Tesseract (default)
$result = LaravelOcr::driver('tesseract')->extract($document);

// Switch to AWS Textract for this request
$result = LaravelOcr::driver('aws_textract')->extract($document);

// Switch to Google Vision
$result = LaravelOcr::driver('google_vision')->extract($document);


$parser = app('laravel-ocr.parser');

$metadata = $parser->extractMetadata('/path/to/document.pdf');

// Returns:
// [
//     'file_name' => 'document.pdf',
//     'file_size' => 102400,
//     'mime_type' => 'application/pdf',
//     'created_at' => '2024-01-15 10:30:00',
//     'modified_at' => '2024-01-15 10:30:00',
//     'pdf_pages' => 3,
//     'pdf_author' => 'John Doe',
//     'pdf_title' => 'Q4 Invoice',
//     'pdf_creator' => 'Microsoft Word',
// ]

use Mayaram\LaravelOcr\Models\ProcessedDocument;

// Query processed documents
$documents = ProcessedDocument::where('document_type', 'invoice')
    ->where('confidence_score', '>=', 0.7)
    ->latest()
    ->get();

foreach ($documents as $doc) {
    // Get a specific field value
    $invoiceNo = $doc->getFieldValue('invoice_number');

    // Get all field values as a flat array
    $allFields = $doc->getAllFieldValues();

    // Check if the result is valid (status=completed & confidence >= 0.7)
    if ($doc->isValid()) {
        // Process the document
    }
}

$processedDocument = [
    'url' => asset('storage/documents/invoice.pdf'),
    'documentId' => $document->id,
    'fields' => [
        [
            'key' => 'invoice_number',
            'label' => 'Invoice Number',
            'value' => 'INV-2024-001',
            'confidence' => 0.95,
            'bounds' => ['x' => 100, 'y' => 50, 'width' => 200, 'height' => 30],
        ],
        // ...more fields
    ],
];

interface OCRDriver
{
    public function extract($document, array $options = []): array;
    public function extractTable($document, array $options = []): array;
    public function extractBarcode($document, array $options = []): array;
    public function extractQRCode($document, array $options = []): array;
    public function getSupportedLanguages(): array;
    public function getSupportedFormats(): array;
}

use Mayaram\LaravelOcr\Contracts\OCRDriver;

class MyCustomDriver implements OCRDriver
{
    public function extract($document, array $options = []): array
    {
        // Your implementation
        return [
            'text' => 'extracted text',
            'confidence' => 0.95,
            'bounds' => [],
            'metadata' => ['engine' => 'custom'],
        ];
    }

    public function extractTable($document, array $options = []): array { /* ... */ }
    public function extractBarcode($document, array $options = []): array { /* ... */ }
    public function extractQRCode($document, array $options = []): array { /* ... */ }
    public function getSupportedLanguages(): array { return ['en' => 'English']; }
    public function getSupportedFormats(): array { return ['jpg', 'png', 'pdf']; }
}

$result = $parser->parse($document, [
    'use_ai_cleanup' => true,
    'provider' => 'basic',
]);

$result = $parser->parse($document, [
    'use_ai_cleanup' => true,
    // Uses LARAVEL_OCR_AI_PROVIDER from config
]);

// Per-call custom prompt
$result = $parser->parse($document, [
    'use_ai_cleanup' => true,
    'custom_prompt' => 'Extract all amounts in INR. Normalize phone numbers to +91 format.',
]);

'ai_cleanup' => [
    'custom_prompt' => 'Always extract Hindi text. Format dates as DD/MM/YYYY.',
],
bash
composer vendor:publish --tag=laravel-ocr-config
php artisan vendor:publish --tag=laravel-ocr-migrations
php artisan migrate
php artisan laravel-ocr:doctor
php artisan laravel-ocr:process storage/app/sample-invoice.pdf --type=invoice
bash
php artisan vendor:publish --tag=laravel-ocr-config
php artisan vendor:publish --tag=laravel-ocr-migrations
php artisan migrate
bash
php artisan vendor:publish --tag=laravel-ocr-views
bash
php artisan laravel-ocr:doctor
bash
php artisan laravel-ocr:doctor
tesseract --version
bash
# Basic
php artisan laravel-ocr:create-template "My Invoice" invoice

# Interactive (prompts for fields, patterns, validators)
php artisan laravel-ocr:create-template "My Invoice" invoice --interactive
bash
php artisan laravel-ocr:doctor