PHP code example of bitdreamit / qz-tray-enterprise

1. Go to this page and download the library: Download bitdreamit/qz-tray-enterprise 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/ */

    

bitdreamit / qz-tray-enterprise example snippets




namespace App\Http\Controllers;

use Illuminate\Http\Request;
use BitDreamIT\QzTray\Facades\QzTray;

class OrderController extends Controller
{
    /**
     * Print receipt for order
     */
    public function printReceipt($orderId)
    {
        $order = Order::with('items', 'customer')->findOrFail($orderId);
        
        // Generate receipt HTML
        $receipt = view('receipts.order', compact('order'))->render();
        
        // Print using ESC/POS format for thermal printer
        QzTray::printEscpos(
            'EPSON TM-T88V',
            $this->generateEscposReceipt($order),
            [
                'copies' => 2,
                'paperSize' => 'Receipt'
            ]
        );
        
        return response()->json([
            'success' => true,
            'message' => 'Receipt sent to printer'
        ]);
    }
    
    /**
     * Print shipping label
     */
    public function printShippingLabel($orderId)
    {
        $order = Order::findOrFail($orderId);
        
        // Generate ZPL label
        $zpl = $this->generateShippingLabelZpl($order);
        
        // Print using Zebra label printer
        QzTray::printZpl('Zebra LP 2844', $zpl, [
            'label_width' => 100,
            'label_height' => 150,
            'copies' => 1
        ]);
        
        return response()->json([
            'success' => true,
            'message' => 'Shipping label printed'
        ]);
    }
    
    /**
     * Print barcode for product
     */
    public function printProductBarcode($productId)
    {
        $product = Product::findOrFail($productId);
        
        // Print barcode label
        QzTray::printBarcode(
            'Zebra LP 2844',
            $product->sku,
            'CODE128',
            [
                'width' => 2,
                'height' => 100,
                'human_readable' => true,
                'copies' => 3
            ]
        );
        
        return response()->json([
            'success' => true,
            'message' => 'Barcode labels printed'
        ]);
    }
    
    /**
     * Print PDF document
     */
    public function printInvoice($orderId)
    {
        $order = Order::findOrFail($orderId);
        
        // Generate PDF
        $pdfUrl = route('orders.invoice.pdf', $order->id);
        
        // Print PDF
        QzTray::printPdf('HP LaserJet', $pdfUrl, [
            'copies' => 1,
            'paperSize' => 'A4',
            'orientation' => 'portrait',
            'pageRange' => '1'
        ]);
        
        return response()->json([
            'success' => true,
            'message' => 'Invoice sent to printer'
        ]);
    }
}



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use BitDreamIT\QzTray\Facades\QzTray;

class PrintJobController extends Controller
{
    /**
     * Get print queue status
     */
    public function queueStatus()
    {
        $status = QzTray::getQueueStatus();
        
        return response()->json([
            'success' => true,
            'data' => $status
        ]);
    }
    
    /**
     * Get print job history
     */
    public function jobHistory(Request $request)
    {
        $limit = $request->input('limit', 50);
        $userId = $request->input('user_id');
        
        $jobs = QzTray::getJobHistory($limit, $userId);
        
        return response()->json([
            'success' => true,
            'data' => $jobs,
            'count' => $jobs->count()
        ]);
    }
    
    /**
     * Cancel print job
     */
    public function cancelJob($jobId)
    {
        $job = PrintJob::findOrFail($jobId);
        
        // Check if job can be cancelled
        if (!$job->isPending()) {
            return response()->json([
                'success' => false,
                'error' => 'Job cannot be cancelled'
            ], 400);
        }
        
        $job->markAsCancelled();
        
        return response()->json([
            'success' => true,
            'message' => 'Job cancelled successfully'
        ]);
    }
    
    /**
     * Clear printer queue
     */
    public function clearQueue(Request $request)
    {
        $request->validate([
            'printer' => '

// In your application service provider
public function boot()
{
    // Set default printers for different modules
    QzTray::saveUserPreference(auth()->id(), 'receipts', 'EPSON TM-T88V');
    QzTray::saveUserPreference(auth()->id(), 'labels', 'Zebra LP 2844');
    QzTray::saveUserPreference(auth()->id(), 'documents', 'HP LaserJet');
    
    // Or in controller actions
    QzTray::saveUserPreference(
        auth()->id(),
        'shipping_labels',
        $request->input('printer')
    );
}

// Retrieve module-specific printer
$labelPrinter = QzTray::getUserPreference(auth()->id(), 'labels');

// Create custom print templates
class ReceiptTemplate
{
    public static function generate(array $orderData): string
    {
        return "
            ^XA
            ^FO50,50^A0N,50,50^FDORDER RECEIPT^FS
            ^FO50,120^A0N,30,30^FDOrder #: {$orderData['number']}^FS
            ^FO50,160^A0N,30,30^FDDate: " . date('Y-m-d H:i:s') . "^FS
            ^FO50,200^A0N,30,30^FDTotal: \${$orderData['total']}^FS
            ^FO50,250^GB700,3,3^FS
            ^FO50,270^A0N,25,25^FDThank you for your order!^FS
            ^XZ
        ";
    }
}

// Usage
$zpl = ReceiptTemplate::generate($order->toArray());
QzTray::printZpl('Zebra LP 2844', $zpl);

// app/Providers/EventServiceProvider.php
protected $listen = [
    \BitDreamIT\QzTray\Events\PrintJobQueued::class => [
        \App\Listeners\LogPrintJob::class,
        \App\Listeners\SendPrintNotification::class,
    ],
    \BitDreamIT\QzTray\Events\PrinterConnected::class => [
        \App\Listeners\UpdatePrinterStatus::class,
    ],
];

// Custom listener example
namespace App\Listeners;

use BitDreamIT\QzTray\Events\PrintJobQueued;

class SendPrintNotification
{
    public function handle(PrintJobQueued $event)
    {
        $job = $event->printJob;
        
        // Send notification to user
        $job->user->notify(new PrintJobNotification($job));
        
        // Log to external system
        ExternalLogService::logPrintJob($job);
    }
}

// Simple text printing
QzTray::printRaw('EPSON TM-T88V', "Hello World\nThis is a test print");

// With ESC/POS commands
$escpos = "\x1B\x40" . // Initialize printer
          "\x1B\x61\x01" . // Center align
          "RECEIPT\n" .
          "\x1B\x61\x00" . // Left align
          "Item 1: $10.00\n" .
          "Item 2: $15.00\n" .
          "\x1D\x56\x41\x10"; // Cut paper

QzTray::printRaw('EPSON TM-T88V', $escpos);

// Print HTML document
$html = '
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; }
            .header { text-align: center; font-size: 24px; }
            .content { margin: 20px; }
        </style>
    </head>
    <body>
        <div class="header">Company Invoice</div>
        <div class="content">
            <p>Invoice #: INV-2023-001</p>
            <p>Date: ' . date('Y-m-d') . '</p>
        </div>
    </body>
    </html>';

QzTray::printHtml('HP LaserJet', $html, [
    'paperSize' => 'A4',
    'orientation' => 'portrait',
    'margins' => '0.5in'
]);

// Print PDF from URL
QzTray::printPdf('HP LaserJet', 'https://example.com/invoice.pdf', [
    'copies' => 2,
    'pageRange' => '1-3',
    'orientation' => 'landscape'
]);

// Print PDF from local file
$pdfPath = storage_path('app/invoices/invoice-123.pdf');
$pdfUrl = asset('storage/invoices/invoice-123.pdf');

QzTray::printPdf('PDF Printer', $pdfUrl, [
    'copies' => 1
]);

// Print image from URL
QzTray::printImage('Photo Printer', 'https://example.com/photo.jpg', [
    'copies' => 1,
    'dpi' => 300,
    'width' => 800,
    'height' => 600
]);

// Print image from local file
$imageUrl = asset('storage/products/barcode.png');
QzTray::printImage('Label Printer', $imageUrl, [
    'dpi' => 203, // Standard label printer DPI
    'width' => 800
]);

// Simple label
$zpl = '^XA
    ^FO50,50^A0N,50,50^FDProduct Label^FS
    ^FO50,120^BY3^BCN,100,Y,N,N^FD123456789012^FS
    ^FO50,250^A0N,30,30^FDSKU: ABC-123^FS
    ^XZ';

QzTray::printZpl('Zebra LP 2844', $zpl, [
    'label_width' => 100,
    'label_height' => 150
]);

// Barcode label with graphics
$zpl = '^XA
    ^FO20,20^GB760,1,3^FS
    ^FO20,40^A0N,40,40^FDWAREHOUSE LABEL^FS
    ^FO20,100^BY3^BCN,150,Y,N,N^FD' . $sku . '^FS
    ^FO20,280^A0N,30,30^FDLocation: ' . $location . '^FS
    ^FO20,320^A0N,30,30^FDQty: ' . $quantity . '^FS
    ^XZ';

QzTray::printZpl('Zebra ZT410', $zpl);

// Complete receipt with formatting
$escpos = "\x1B\x40" . // Initialize
          "\x1B\x61\x01" . // Center
          "RESTAURANT NAME\n" .
          "123 Main Street\n" .
          "Phone: (555) 123-4567\n" .
          "\x1B\x61\x00" . // Left
          "\x1B\x45\x01" . // Bold on
          "ORDER #: 2023-00123\n" .
          "\x1B\x45\x00" . // Bold off
          str_repeat("-", 42) . "\n" .
          "Item              Qty   Price   Total\n" .
          str_repeat("-", 42) . "\n" .
          "Burger            2     $10.00  $20.00\n" .
          "Fries             1     $4.00   $4.00\n" .
          "Soda              1     $2.50   $2.50\n" .
          str_repeat("-", 42) . "\n" .
          "\x1B\x45\x01" . // Bold
          "Total:                    $26.50\n" .
          "\x1B\x45\x00" . // Bold off
          "\x1B\x61\x01" . // Center
          "Thank you for dining with us!\n" .
          "\x1D\x56\x41\x10"; // Cut

QzTray::printEscpos('EPSON TM-T88V', $escpos);

// Middleware automatically enforces HTTPS
// For local development, add to .env:
QZ_ALLOW_LOCALHOST=true

// Default middleware ', 'auth'],

// Customize in config/qz-tray.php
'middleware' => ['web', 'auth', 'role:admin,manager'],

// Add to .env
QZ_TRUSTED_IPS=192.168.1.0/24,10.0.0.0/8

// Or in config
'trusted_ips' => explode(',', env('QZ_TRUSTED_IPS', '')),

// Run printer discovery
QzTray::printerService()->refresh();

// Check system printers
$printers = QzTray::getAllPrinters();
dd($printers);

// Clear printer queue
QzTray::clearQueue('Printer Name');

// Check job status
$job = PrintJob::find($jobId);
if ($job->isPending()) {
    $job->markAsFailed('Manual intervention 

// Cache printer discovery (5 minutes)
Cache::remember('qz_printers', 300, function () {
    return QzTray::getAllPrinters();
});

// Cache capabilities (10 minutes)
Cache::remember('qz_capabilities_' . $printerName, 600, function () use ($printerName) {
    return QzTray::getPrinterCapabilities($printerName);
});

// Use database queue for print jobs
'queue' => [
    'default' => 'database',
    'connections' => [
        'database' => [
            'driver' => 'database',
            'table' => 'jobs',
            'queue' => 'print',
            'retry_after' => 90,
        ],
    ],
],

// Before: Manual QZ Tray implementation
$config = qz.configs.create('Printer');
qz.print($config, ['Hello World']);

// After: Using QZ Tray Enterprise
QzTray::printRaw('Printer', 'Hello World');

// Before: Using another package
$printer = new ThermalPrinter('EPSON TM-T88V');
$printer->text('Hello World');
$printer->cut();

// After: Using QZ Tray Enterprise
$escpos = "Hello World\n\x1D\x56\x41\x10";
QzTray::printEscpos('EPSON TM-T88V', $escpos);
bash
php artisan qz-tray:install
bash
php artisan qz-tray:generate-certificate
bash
php artisan migrate
bash
php artisan vendor:publish --tag=qz-tray-config
bash
# Run full diagnostics
php artisan tinker
>>> QzTray::getSystemStatus();

# Check inker
>>> QzTray::getAllPrinters();

# Test print
php artisan tinker
>>> QzTray::testPrint('Printer Name');
bash
# Run all tests
php artisan test

# Run specific test suite
php artisan test --testsuite=Unit
php artisan test --testsuite=Feature

# Generate test coverage
vendor/bin/phpunit --coverage-html coverage