您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# PHP如何实现小票打印
在零售、餐饮等行业中,小票打印是常见的业务需求。PHP作为服务端语言,可以通过多种方式实现小票打印功能。本文将介绍几种主流实现方案及其核心代码示例。
## 一、直接连接打印机打印
### 1. 使用PHP Printer扩展(Windows环境)
```php
<?php
$printer = "POS-58"; // 打印机名称
$handle = printer_open($printer);
printer_start_doc($handle, "Receipt");
printer_start_page($handle);
// 设置字体
$font = printer_create_font("Arial", 72, 48, PRINTER_FW_NORMAL, false, false, false, 0);
printer_select_font($handle, $font);
// 打印内容
printer_draw_text($handle, "=== 销售小票 ===", 100, 100);
printer_draw_text($handle, date('Y-m-d H:i:s'), 100, 200);
printer_end_page($handle);
printer_end_doc($handle);
printer_close($handle);
?>
注意:需要安装php_printer.dll
扩展并启用
$escpos = "
\x1B@\x1B!\x38\x1D!\x11
=== 销售小票 ===\n
商品A ¥15.00\n
商品B ¥20.00\n
----------------\n
总计: ¥35.00\n
\x1D\x56\x41"; // 切纸指令
file_put_contents("//192.168.1.100/printer", $escpos);
$data = [
'header' => "XX商店",
'items' => [
['name' => '商品A', 'price' => 15],
['name' => '商品B', 'price' => 20]
],
'footer' => "谢谢惠顾"
];
$ch = curl_init('http://print-service/api/print');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
$result = curl_exec($ch);
curl_close($ch);
前端方案:
window.print();
PHP生成打印模板:
<?php
$html = <<<HTML
<!DOCTYPE html>
<html>
<head>
<style>
@media print {
body { width: 58mm; font-size: 12px; }
.no-print { display: none; }
}
</style>
</head>
<body>
<h2>{$shopName}</h2>
<div>{$orderDetails}</div>
<button class="no-print" onclick="window.print()">打印</button>
</body>
</html>
HTML;
echo $html;
?>
使用TCPDF库:
require_once('tcpdf/tcpdf.php');
$pdf = new TCPDF('P', 'mm', [58, 200], true, 'UTF-8', false);
$pdf->AddPage();
$pdf->SetFont('stsongstdlight', '', 10);
$pdf->Cell(0, 0, "=== 销售小票 ===", 0, 1);
$pdf->Output('receipt.pdf', 'I'); // I: 内联输出,F: 保存文件
$api = "https://api.weixin.qq.com/device/transmsg?access_token={$token}";
$data = [
'device_type' => 'printer',
'device_id' => $deviceId,
'print_content' => $receiptContent
];
// 发送HTTP请求...
function printReceipt($items, $total) {
$printerIP = "192.168.1.100";
$port = 9100;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, $printerIP, $port);
$output = "\x1B@"; // 初始化打印机
$output .= "\x1B!\x08"; // 设置字体
$output .= "销售小票\n\n";
foreach($items as $item) {
$output .= sprintf("%-12s %6s\n",
mb_substr($item['name'], 0, 12),
'¥'.$item['price']);
}
$output .= "----------------\n";
$output .= sprintf("%-12s %6s\n", "总计:", '¥'.$total);
$output .= "\x1D\x56\x41"; // 切纸
socket_write($socket, $output);
socket_close($socket);
}
以上方案可根据实际业务场景组合使用,建议生产环境采用中间件方案提高可靠性。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。