php实现小票打印
PHP 实现小票打印的方法
使用 ESC/POS 指令直接打印
ESC/POS 是一种常见的打印机指令集,适用于热敏打印机和点阵打印机。PHP 可以通过发送原始指令控制打印机。
// 连接打印机(假设通过 USB 或网络)
$printer = fopen("php://temp", "r+");
// 发送初始化指令
fwrite($printer, "\x1B\x40");
// 设置居中打印
fwrite($printer, "\x1B\x61\x31");
// 打印标题
fwrite($printer, "=== 销售小票 ===\n");
// 设置左对齐
fwrite($printer, "\x1B\x61\x30");
// 打印商品信息
fwrite($printer, "商品1 10.00\n");
fwrite($printer, "商品2 20.00\n");
// 打印总计
fwrite($printer, "----------------\n");
fwrite($printer, "总计: 30.00\n");
// 切纸
fwrite($printer, "\x1D\x56\x41\x03");
fclose($printer);
使用现成的 PHP 库
mike42/escpos-php 是一个流行的 PHP 库,封装了 ESC/POS 指令。
require __DIR__ . '/vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\NetworkPrintConnector;
try {
$connector = new NetworkPrintConnector("192.168.1.100", 9100);
$printer = new Printer($connector);
$printer->setJustification(Printer::JUSTIFY_CENTER);
$printer->text("=== 销售小票 ===\n");
$printer->setJustification(Printer::JUSTIFY_LEFT);
$printer->text("商品1 10.00\n");
$printer->text("商品2 20.00\n");
$printer->text("----------------\n");
$printer->text("总计: 30.00\n");
$printer->cut();
$printer->close();
} catch (Exception $e) {
echo "打印失败: " . $e->getMessage();
}
通过浏览器打印
如果需要从网页打印小票,可以使用 JavaScript 的 window.print() 方法。
// PHP 生成 HTML 小票
echo '<div id="receipt" style="width:80mm; font-family: monospace;">
<h2 style="text-align:center;">=== 销售小票 ===</h2>
<p>商品1 10.00</p>
<p>商品2 20.00</p>
<hr>
<p>总计: 30.00</p>
</div>';
// JavaScript 打印
echo '<script>window.onload = function() { window.print(); }</script>';
使用 CUPS 打印服务
在 Linux 系统上,可以通过 CUPS 服务打印。
// 生成 PDF 或文本文件
file_put_contents('/tmp/receipt.txt', "=== 销售小票 ===\n商品1 10.00\n商品2 20.00\n总计: 30.00");
// 使用 lpr 命令打印
exec('lpr -P receipt_printer /tmp/receipt.txt');
云打印解决方案
对于云打印需求,可以使用 Google Cloud Print 或其他云打印 API。
$receiptContent = "=== 销售小票 ===\n商品1 10.00\n商品2 20.00\n总计: 30.00";
$printJob = array(
'title' => '销售小票',
'content' => base64_encode($receiptContent),
'contentType' => 'text/plain'
);
// 发送到云打印服务
$ch = curl_init('https://www.google.com/cloudprint/submit');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $printJob);
curl_exec($ch);
curl_close($ch);
注意事项
- 确保打印机支持 ESC/POS 指令集
- 网络打印机需要正确配置 IP 和端口
- 浏览器打印需要用户确认
- 云打印服务可能需要 OAuth 认证







