You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP CodeIgniter框架的POS软件中实现无弹窗直接打印小票

Alright, let's tackle this problem—your current CodeIgniter POS setup uses window.print() which triggers the browser's print dialog, adding those extra 3-4 steps you want to eliminate. Here are practical, POS-friendly solutions to get direct, dialog-free printing working:

CodeIgniter POS: Direct Dialog-Free Receipt Printing

Option 1: Chrome Kiosk Printing (Best for Fixed Cashier Devices)

If your POS runs on Chrome (super common for dedicated terminals), you can configure Chrome to skip the print dialog entirely and send jobs straight to your receipt printer.

Setup Steps:

  1. Create a Chrome shortcut (right-click Chrome > Create shortcut)
  2. Right-click the new shortcut > Properties
  3. In the Target field, add these flags at the end (replace with your printer name):
    --kiosk-printing --disable-print-preview --printer="Your Receipt Printer Name"
    
  4. Launch Chrome via this shortcut. Now when your window.print() runs, Chrome will print directly to the specified printer without any popups.

Option 2: Backend PDF Generation + Server-Side Printing (Best for Network Printers)

Use CodeIgniter's backend to generate a receipt PDF, then send it directly to your printer via server commands. This works great if your printer is connected to your server or on the same network.

Step 1: Install a PDF Library

We'll use Dompdf (easy to integrate with CodeIgniter):

composer require dompdf/dompdf

Step 2: Build a Print Controller

Create a controller to generate the receipt PDF and trigger printing:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Receipt_printer extends CI_Controller {
    public function print_order($order_id) {
        // Load Dompdf
        require_once APPPATH.'vendor/autoload.php';
        use Dompdf\Dompdf;

        // Fetch order data from your database
        $order = $this->db->get_where('orders', ['id' => $order_id])->row();
        $order_items = $this->db->get_where('order_items', ['order_id' => $order_id])->result();

        // Build your receipt HTML (tailor this to your POS's branding)
        $receipt_html = '
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <style>
                body { font-family: "Courier New", monospace; font-size: 12px; margin: 0 10px; }
                .header { text-align: center; margin-bottom: 8px; }
                .divider { border-top: 1px dashed #000; margin: 6px 0; }
                .items { margin: 8px 0; }
                .total { text-align: right; font-weight: bold; margin-top: 8px; }
            </style>
        </head>
        <body>
            <div class="header">
                <h3>Your Store Name</h3>
                <p>123 Main St | 555-1234</p>
            </div>
            <div class="divider"></div>
            <p>Order #'.$order->order_number.'</p>
            <p>Date: '.date('m/d/Y h:i A', strtotime($order->created_at)).'</p>
            <div class="divider"></div>
            <div class="items">
                <table width="100%">
                    <tr><th>Item</th><th>Qty</th><th>Price</th></tr>';
                    foreach($order_items as $item) {
                        $receipt_html .= '<tr><td>'.$item->product_name.'</td><td>'.$item->quantity.'</td><td>$'.$item->unit_price.'</td></tr>';
                    }
                $receipt_html .= '</table>
            </div>
            <div class="divider"></div>
            <div class="total">
                <p>Subtotal: $'.$order->subtotal.'</p>
                <p>Tax: $'.$order->tax.'</p>
                <p>Total: <strong>$'.$order->total.'</strong></p>
            </div>
            <div class="divider"></div>
            <p style="text-align:center;">Thank you for your business!</p>
        </body>
        </html>';

        // Generate PDF
        $dompdf = new Dompdf();
        $dompdf->loadHtml($receipt_html);
        $dompdf->setPaper('A5', 'portrait'); // Match your receipt paper size
        $dompdf->render();

        // Save temp PDF file
        $temp_pdf = FCPATH.'temp_receipt.pdf';
        file_put_contents($temp_pdf, $dompdf->output());

        // Send to printer (adjust command for your OS)
        // Linux/macOS (use lp command):
        exec('lp -d "Your Printer Name" '.$temp_pdf);
        // Windows (use print command):
        // exec('print /d:"Your Printer Name" '.$temp_pdf);

        // Clean up temp file
        unlink($temp_pdf);

        // Return success response
        echo json_encode(['status' => 'success']);
    }
}

Step 3: Update Frontend Button

Replace your existing print function with an API call to the backend:

function PrintTicket(orderId) {
    fetch(`/receipt_printer/print_order/${orderId}`)
        .then(res => res.json())
        .then(data => {
            if(data.status === 'success') {
                alert('Receipt sent to printer!');
            } else {
                alert('Print failed—please try again.');
            }
        })
        .catch(err => {
            console.error('Print error:', err);
            alert('Something went wrong with printing.');
        });
}

Update your HTML button to pass the order ID:

<button type="button" class="btn btn-add hiddenpr" onclick="PrintTicket(<?=$order->id;?>)"><?=label("print");?></button>

Option 3: Web Bluetooth/USB Printing (Best for Wireless Receipt Printers)

If you have a Bluetooth/USB-enabled thermal receipt printer, you can use Web APIs to send print commands directly from the browser. Note: This requires browser support (Chrome/Edge work best) and a one-time user authorization.

Example Web Bluetooth Code:

async function PrintTicket() {
    try {
        // Connect to your Bluetooth receipt printer (check your device's service UUID)
        const device = await navigator.bluetooth.requestDevice({
            filters: [{ services: ['000018f0-0000-1000-8000-00805f9b34fb'] }]
        });
        const server = await device.gatt.connect();
        const service = await server.getPrimaryService('000018f0-0000-1000-8000-00805f9b34fb');
        const characteristic = await service.getCharacteristic('00002af1-0000-1000-8000-00805f9b34fb');

        // Build receipt content (use ESC/POS commands if your printer supports them)
        const receipt = `
            Your Store Name
            123 Main St | 555-1234
            ------------------------
            Order #12345
            05/20/2024 02:30 PM
            ------------------------
            Cola x1 $3.00
            Burger x2 $15.00
            ------------------------
            Total: $18.00
            Thank you!
            \n\n\n`; // Extra newlines to feed paper

        // Send to printer
        const encoder = new TextEncoder();
        await characteristic.writeValue(encoder.encode(receipt));

        alert('Receipt printed successfully!');
    } catch(error) {
        console.error('Print error:', error);
        alert('Failed to print—check printer connection.');
    }
}

Quick Notes:

  • Option 1 is the simplest for fixed terminals—no code changes needed, just Chrome configuration.
  • Option 2 works best for networked printers and gives you full control over receipt formatting.
  • Option 3 is great for wireless setups but requires printer compatibility.

Pick the option that fits your POS hardware and workflow!

内容的提问来源于stack exchange,提问作者amir ashfaq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:05:43