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 the package:

    composer require mike42/escpos-php
    
  2. Verify PHP extensions (required):

    php -m | grep json,intl,zlib
    

    Install missing extensions (e.g., sudo apt-get install php-json php-intl php-zlib on Ubuntu).

  3. First use case: Print a simple receipt via Ethernet (replace 192.168.1.100 with your printer’s IP):

    use Mike42\Escpos\PrintConnectors\NetworkPrintConnector;
    use Mike42\Escpos\Printer;
    
    $connector = new NetworkPrintConnector("192.168.1.100", 9100);
    $printer = new Printer($connector);
    $printer->text("Hello, ESC/POS!\n");
    $printer->cut();
    $printer->close();
    

Key Starting Points

  • Examples: Browse example/ for OS/interface-specific setups (e.g., ethernet.php, linux-usb.php).
  • Printer Profiles: Use CapabilityProfile::load("simple") for unknown printers or SP2000 for Star-branded devices.
  • Debugging: Redirect output to a file first (php script.php > output.esc) to verify commands before printing.

Implementation Patterns

Core Workflow

  1. Initialize Printer:
    $printer = new Printer(
        new NetworkPrintConnector("192.168.1.100", 9100),
        CapabilityProfile::load("default") // or "simple" for basic features
    );
    
  2. Format Receipts:
    $printer->selectPrintMode(Printer::MODE_DOUBLE_HEIGHT);
    $printer->text("STORE NAME\n");
    $printer->setJustification(Printer::JUSTIFY_CENTER);
    $printer->text("RECEIPT #12345\n");
    $printer->setEmphasis(true); // Bold text
    $printer->text("ITEM: Coffee\n");
    $printer->setEmphasis(false);
    $printer->text("Price: $2.50\n");
    
  3. Add Graphics/Barcodes:
    // Logo (requires GD/Imagick)
    $logo = EscposImage::load("logo.png");
    $printer->graphics($logo, Printer::IMG_DOUBLE_HEIGHT);
    
    // Barcode (UPC-A)
    $printer->barcode("123456789012", Printer::BARCODE_UPCA);
    
  4. Cut & Close:
    $printer->cut(Printer::CUT_FULL);
    $printer->close();
    

Integration Tips

  • Queue Jobs: For web apps, use a queue (e.g., Laravel Queues) to avoid timeouts:
    dispatch(new PrintReceiptJob($orderId, $printerIp));
    
  • Templates: Create reusable receipt templates as classes:
    class ReceiptTemplate {
        public function __invoke(Printer $printer, array $data) {
            $printer->text($data['store_name']);
            // ... render items, totals, etc.
        }
    }
    
  • Error Handling: Wrap printer operations in try-catch:
    try {
        $printer->text("Error test");
    } catch (Exception $e) {
        Log::error("Print failed: " . $e->getMessage());
    }
    

Common Patterns

Use Case Implementation Notes
Multi-language Set code page: $printer->setCodePage(Printer::CODEPAGE_CP1252); Use CP1252 for Western European chars.
Partial Cuts $printer->cut(Printer::CUT_PARTIAL, 2); Feeds 2 lines before cutting.
Images $printer->graphics($image, Printer::IMG_DOUBLE_WIDTH); Optimize images to 300 DPI for clarity.
QR Codes Use pdf417Code() for 2D codes. Limited to PDF417 standard.

Gotchas and Tips

Pitfalls

  1. Printer-Specific Quirks:

    • Epson TM-T20: Requires feedForm() to release paper (not implemented in this driver; use cut() instead).
    • Star TSP100: Use CapabilityProfile::load("SP2000") for correct commands.
    • USB Permissions: On Linux, ensure your user has access to /dev/usb/lp*:
      sudo usermod -a -G lp $USER
      
    • Windows SMB: Share the printer first (\\server\printer) and use WindowsPrintConnector.
  2. Encoding Issues:

    • Default UTF-8 may fail on some printers. Force ASCII:
      $printer->setCodePage(Printer::CODEPAGE_ISO);
      
    • For non-Latin scripts, use mb_convert_encoding() before printing.
  3. Image Problems:

    • Error: Failed to load image. Ensure:
      • The image path is correct (use absolute paths in production).
      • GD/Imagick is installed (php -m | grep gd,imagick).
      • Images are < 200KB (thermal printers have limited memory).
    • Fix: Convert images to grayscale (imagefilter($img, IMG_FILTER_GRAYSCALE)) for better compatibility.
  4. Network Timeouts:

    • Ethernet printers may hang if the connection drops. Add a timeout:
      $connector = new NetworkPrintConnector("192.168.1.100", 9100, 2.0); // 2-second timeout
      
  5. Partial Prints:

    • If a receipt cuts off, increase the cut() lines parameter or check printer paper sensors.

Debugging Tips

  • Log Raw Commands: Redirect output to a file and inspect with a hex editor:
    $connector = new FilePrintConnector("php://temp");
    // ... print commands ...
    file_put_contents("debug.esc", file_get_contents("php://temp"));
    
  • Test with escpos-php's CLI Tool:
    composer require mike42/escpos-php-cli
    escpos-php --help
    
  • Check Printer Status: Some printers require a manual "feed" after power-on. Send an empty print job first:
    $printer->text("\n\n"); // Force feed
    

Extension Points

  1. Custom PrintConnectors:

    • Extend PrintConnector for proprietary protocols (e.g., Bluetooth):
      class BluetoothPrintConnector extends PrintConnector {
          public function write($data) {
              // Implement Bluetooth socket logic
          }
      }
      
    • Register in composer.json:
      "autoload": {
          "psr-4": {
              "App\\PrintConnectors\\": "src/PrintConnectors"
          }
      }
      
  2. Dynamic Profiles:

    • Load printer profiles dynamically based on model:
      $profile = CapabilityProfile::load($this->getPrinterModel());
      
    • Store profiles in a database and hydrate them:
      $profile = new CapabilityProfile(json_decode($dbProfile));
      
  3. Fallbacks:

    • Use bitImage() for printers without graphics() support:
      $printer->bitImage($image, Printer::IMG_DOUBLE_WIDTH);
      
    • Implement a FallbackPrintConnector that retries with a different interface if the primary fails.
  4. Testing:

    • Mock PrintConnector in unit tests:
      $mockConnector = $this->createMock(PrintConnector::class);
      $mockConnector->method('write')->willReturn(true);
      $printer = new Printer($mockConnector);
      
    • Use FilePrintConnector to test without a real printer.

Configuration Quirks

  • Code Pages: Not all printers support UTF-8. Test these common pages:
    • CODEPAGE_CP1252 (Western European)
    • CODEPAGE_ISO (ISO-8859-1)
    • CODEPAGE_GB18030 (Chinese)
  • Barcode Limits: Some printers cap barcode height/width. Adjust dynamically:
    $height = min($printer->getMaxBarcodeHeight(),
    
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.
calmfox/watch-sylius
damienfern/grpc-symfony-bundle
atoolo/index-bundle
atoolo/genai-bundle
coprotoai/laravel-ticket
davidjln/llm-carbon-bundle
cryonighter/valid-request-bundle
coolms/taxonomy-bundle
coolms/field-bundle
articulate-orm/symfony
aaix/laravel-tall-architect
ephoto/akeneo-connector
emmanuelballery/eb-plantumlbundle
emielburgman/symfony-visitor-beacon
emielburgman/symfony-visit-storage
emielburgman/symfony-security-headers
emielburgman/symfony-log-viewer
emarref/xdebug-bundle
emarref/pubnub-bundle
elriseio/finance-money-bundle