Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Escpos Php Laravel Package

mike42/escpos-php

PHP library for ESC/POS receipt printers. Print text, images, barcodes, QR codes and cut paper over USB, network, serial or Windows share. Includes connectors and utilities for common thermal POS printers and cash drawers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install via Composer:

    composer require mike42/escpos-php
    
  2. Basic Usage Example (Network Printer):

    use Mike42\Escpos\PrintConnectors\NetworkPrintConnector;
    use Mike42\Escpos\Printer;
    
    $connector = new NetworkPrintConnector("192.168.1.100", 9100);
    $printer = new Printer($connector);
    $printer->text("Hello World!\n");
    $printer->cut();
    $printer->close();
    
  3. First Use Case:

    • Print a simple receipt with itemized text, alignment, and a cut command.
    • Test with a USB/serial printer first (easier debugging).

Where to Look First

  • Documentation (Wiki is comprehensive)
  • src/Mike42/Escpos/ (Core classes: Printer, PrintConnectors, Graphics)
  • tests/ (Real-world examples for barcodes, QR codes, and formatting)

Implementation Patterns

Core Workflows

  1. Receipt Generation Pipeline:

    $printer = new Printer($connector);
    $printer->selectPrintMode(Printer::MODE_DOUBLE_HEIGHT);
    $printer->setJustification(Printer::JUSTIFY_CENTER);
    $printer->text("ORDER #12345\n");
    $printer->text("Item 1: $10.00\n");
    $printer->text("Item 2: $5.00\n");
    $printer->text("Total: $15.00\n", 1, Printer::FONT_B);
    $printer->cut(Printer::CUT_PARTIAL);
    $printer->close();
    
  2. Dynamic Data Binding (Laravel Blade Example):

    // In a controller:
    $order = Order::find($id);
    $printer = new Printer($connector);
    $printer->text("Order #{$order->id}\n");
    $printer->text("Customer: {$order->customer_name}\n");
    $printer->qr("https://example.com/order/{$order->id}", 50);
    
  3. Connection Management:

    • USB/Serial: Use SerialPrintConnector (requires php-serial extension).
      $connector = new SerialPrintConnector("/dev/usb/lp0");
      
    • Network: Default for most POS systems (port 9100 is standard).
    • File Output: For testing/debugging:
      $connector = new FilePrintConnector("output.escpos");
      
  4. Barcodes & QR Codes:

    $printer->barcode("123456789", Printer::TYPE_CODE128);
    $printer->qr("https://example.com", 30);
    
  5. Cash Drawer Integration:

    $printer->pulse(255, 100); // Open drawer (adjust pulse duration as needed)
    

Integration Tips

  • Laravel Service Provider: Bind the printer connector in AppServiceProvider for dependency injection:
    $this->app->singleton('printer', function ($app) {
        return new Printer(new NetworkPrintConnector(config('printer.ip'), config('printer.port')));
    });
    
  • Queue Jobs for Async Printing:
    class PrintReceiptJob implements ShouldQueue
    {
        public function handle()
        {
            $printer = app('printer');
            // ... print logic ...
        }
    }
    
  • Template System: Create a ReceiptBuilder class to encapsulate common layouts:
    class ReceiptBuilder {
        public function build(Order $order) {
            $printer = new Printer($connector);
            $printer->text("=== RECEIPT ===");
            foreach ($order->items as $item) {
                $printer->text("{$item->name}: ${item->price}");
            }
            $printer->cut();
            return $printer;
        }
    }
    

Gotchas and Tips

Common Pitfalls

  1. Connection Issues:

    • Network Printers: Ensure the printer’s IP is static or use mDNS (avahi://).
    • Firewalls: Port 9100 (default) may be blocked. Test with telnet <IP> 9100.
    • USB Permissions: On Linux, add user to lp group or adjust /etc/udev/rules.d/.
  2. Encoding Problems:

    • Use utf8 encoding explicitly:
      $printer->setCharacterCode('UTF-8');
      $printer->text("Café"); // Works with UTF-8
      
    • Fallback: Use Printer::CHARCODE_ISO for non-UTF8 printers.
  3. Paper Feed Quirks:

    • cut() may not work on all printers. Use feed(50) (50 dots) as a fallback.
    • Partial cuts (CUT_PARTIAL) may tear paper; test with CUT_FULL.
  4. Memory Limits:

    • Large images/barcodes may hit PHP’s memory_limit. Stream output for big receipts:
      $printer->open();
      $printer->text("Large Data...");
      $printer->close(); // Flushes immediately
      
  5. Driver Compatibility:

    • Not all ESC/POS printers support the same commands. Test with:
      $printer->raw(Printer::ESC_ALIGN_CENTER);
      
    • Check the printer database for known issues.

Debugging Tips

  • Log Raw Commands: Extend Printer to log output:
    $printer = new Printer($connector);
    $printer->setDebug(true); // Logs to stderr
    
  • Test with FilePrintConnector: Save output to a file and open it in a hex editor to verify commands.
  • Common Errors:
    • Connection refused: Printer offline or wrong IP/port.
    • Invalid argument: Check barcode/Qr code size limits (max ~200px width).
    • No data: Ensure close() is called to flush buffers.

Extension Points

  1. Custom Connectors: Extend PrintConnector for proprietary protocols:
    class CustomPrintConnector extends PrintConnector {
        public function write($data) {
            // Implement custom logic (e.g., HTTP API calls)
        }
    }
    
  2. Printer Profiles: Create a PrinterConfig class to manage device-specific settings:
    class PrinterConfig {
        public static function getForModel(string $model) {
            return match ($model) {
                'pos58' => ['width' => 202, 'timeout' => 5000],
                default => ['width' => 384],
            };
        }
    }
    
  3. Laravel Notifications: Use the package with Laravel’s notification system for order confirmations:
    Notification::route('printer', $printer)
                ->notify(new PrintReceipt($order));
    
  4. Image Handling: For high-res images, use Printer::IMAGE_MODE_DOUBLE_HEIGHT or scale down:
    $printer->graphics(file_get_contents('logo.png'), 200, 50);
    

Configuration Quirks

  • Timeouts: Default timeout is 2 seconds. Increase for slow networks:
    $connector = new NetworkPrintConnector("192.168.1.100", 9100, 5000); // 5s timeout
    
  • Line Spacing: Use setLineSpacing() for multi-line items:
    $printer->setLineSpacing(30); // 30 dots = ~1.5 lines
    
  • Font Limits: FONT_B (bold) may not be supported on all printers. Test with FONT_A (normal).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui