php实现小票打印
PHP 实现小票打印的方法
使用 ESC/POS 指令直接打印
ESC/POS 是一种常见的热敏打印机指令集,可以通过 PHP 直接发送指令到打印机。需要确保打印机支持 ESC/POS 协议。
<?php
$printer = fopen("php://stdout", "w"); // 实际使用时替换为打印机设备路径,如 '/dev/usb/lp0'
fwrite($printer, "\x1B@"); // 初始化打印机
fwrite($printer, "=== 销售小票 ===\n");
fwrite($printer, "商品: 测试商品 数量: 1\n");
fwrite($printer, "金额: ¥10.00\n");
fwrite($printer, "\x1B\x69"); // 切纸指令
fclose($printer);
?>
通过 HTML/CSS 生成打印内容
使用 HTML 和 CSS 设计小票模板,通过浏览器打印功能或转换为 PDF 后打印。
<!DOCTYPE html>
<html>
<head>
<style>
.receipt {
width: 80mm;
font-family: Arial;
padding: 10px;
}
.title {
text-align: center;
font-weight: bold;
margin-bottom: 10px;
}
.item {
display: flex;
justify-content: space-between;
margin: 5px 0;
}
</style>
</head>
<body>
<div class="receipt">
<div class="title">=== 销售小票 ===</div>
<div class="item">
<span>商品: 测试商品</span>
<span>数量: 1</span>
</div>
<div class="item">
<span>金额:</span>
<span>¥10.00</span>
</div>
</div>
</body>
</html>
使用第三方库
安装 mike42/escpos-php 库可以简化 ESC/POS 打印操作。
<?php
require __DIR__ . '/vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
$connector = new FilePrintConnector("/dev/usb/lp0");
$printer = new Printer($connector);
$printer->text("=== 销售小票 ===\n");
$printer->text("商品: 测试商品 数量: 1\n");
$printer->text("金额: ¥10.00\n");
$printer->cut();
$printer->close();
?>
通过网络打印
如果打印机支持网络打印,可以通过 TCP/IP 连接发送打印数据。
<?php
$socket = fsockopen("192.168.1.100", 9100); // 打印机IP和端口
fwrite($socket, "\x1B@"); // 初始化
fwrite($socket, "=== 销售小票 ===\n");
fwrite($socket, "商品: 测试商品 数量: 1\n");
fwrite($socket, "金额: ¥10.00\n");
fwrite($socket, "\x1B\x69"); // 切纸
fclose($socket);
?>
转换为 PDF 打印
使用 tcpdf 或 dompdf 库生成 PDF 小票,然后发送到打印机。
<?php
require_once('tcpdf/tcpdf.php');
$pdf = new TCPDF('P', 'mm', array(80, 200), true, 'UTF-8', false);
$pdf->AddPage();
$pdf->SetFont('helvetica', '', 10);
$pdf->Cell(0, 0, '=== 销售小票 ===', 0, 1);
$pdf->Cell(0, 0, '商品: 测试商品 数量: 1', 0, 1);
$pdf->Cell(0, 0, '金额: ¥10.00', 0, 1);
$pdf->Output('receipt.pdf', 'I'); // 在浏览器中打开或发送到打印机
?>
注意事项
- 直接连接打印机需要服务器有访问硬件设备的权限
- 网络打印需要确保防火墙允许对应端口通信
- 热敏打印机通常支持 ESC/POS 指令集,但不同型号可能有差异
- 打印内容宽度应考虑小票纸的实际尺寸(通常 58mm 或 80mm)
以上方法可根据实际需求选择,直接 ESC/POS 打印效率最高,HTML/PDF 方式更灵活但需要额外转换步骤。







