php实现打印票据
PHP 实现打印票据的方法
使用 PHP 直接生成打印内容
PHP 可以通过生成 HTML 或文本格式的内容,直接输出到打印机。以下是一个简单的示例:
<?php
// 设置内容类型为纯文本
header('Content-Type: text/plain');
// 票据内容
$receipt = "=== 收据 ===\n";
$receipt .= "日期: " . date('Y-m-d H:i:s') . "\n";
$receipt .= "项目: 商品A\n";
$receipt .= "数量: 1\n";
$receipt .= "价格: 100元\n";
$receipt .= "================\n";
// 输出到浏览器或打印机
echo $receipt;
?>
使用 TCPDF 或 FPDF 生成 PDF 票据
TCPDF 和 FPDF 是常用的 PHP 库,用于生成 PDF 文件,适合打印票据。
安装 TCPDF:
composer require tecnickcom/tcpdf
示例代码:
<?php
require_once('tcpdf/tcpdf.php');
// 创建 PDF 对象
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
// 设置文档信息
$pdf->SetCreator('POS System');
$pdf->SetAuthor('POS System');
$pdf->SetTitle('收据');
// 添加一页
$pdf->AddPage();
// 设置字体
$pdf->SetFont('stsongstdlight', '', 12);
// 添加内容
$pdf->Cell(0, 10, '=== 收据 ===', 0, 1);
$pdf->Cell(0, 10, '日期: ' . date('Y-m-d H:i:s'), 0, 1);
$pdf->Cell(0, 10, '项目: 商品A', 0, 1);
$pdf->Cell(0, 10, '数量: 1', 0, 1);
$pdf->Cell(0, 10, '价格: 100元', 0, 1);
$pdf->Cell(0, 10, '================', 0, 1);
// 输出 PDF 文件
$pdf->Output('receipt.pdf', 'I');
?>
使用 ESC/POS 指令打印小票
对于热敏打印机,可以使用 ESC/POS 指令直接控制打印机。

安装 escpos-php:
composer require mike42/escpos-php
示例代码:
<?php
require __DIR__ . '/vendor/autoload.php';
use Mike42\Escpos\Printer;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
try {
// 连接到打印机(Windows 使用共享打印机,Linux 使用设备文件)
$connector = new FilePrintConnector("//localhost/POS Printer");
$printer = new Printer($connector);
// 打印内容
$printer->text("=== 收据 ===\n");
$printer->text("日期: " . date('Y-m-d H:i:s') . "\n");
$printer->text("项目: 商品A\n");
$printer->text("数量: 1\n");
$printer->text("价格: 100元\n");
$printer->text("================\n");
// 切纸
$printer->cut();
// 关闭连接
$printer->close();
} catch (Exception $e) {
echo "打印失败: " . $e->getMessage();
}
?>
使用 JavaScript 调用浏览器打印功能
如果票据需要在浏览器中打印,可以结合 PHP 和 JavaScript。

PHP 生成 HTML:
<?php
echo '<html>
<head>
<title>收据</title>
<style>
@media print {
body { font-family: Arial; font-size: 12pt; }
.no-print { display: none; }
}
</style>
</head>
<body>
<h3>=== 收据 ===</h3>
<p>日期: ' . date('Y-m-d H:i:s') . '</p>
<p>项目: 商品A</p>
<p>数量: 1</p>
<p>价格: 100元</p>
<p>================</p>
<button class="no-print" onclick="window.print()">打印</button>
</body>
</html>';
?>
使用 PHP 打印到网络打印机
通过 PHP 的 fsockopen 可以直接发送数据到网络打印机。
示例代码:
<?php
$printer_ip = '192.168.1.100';
$printer_port = 9100;
$receipt = "=== 收据 ===\n";
$receipt .= "日期: " . date('Y-m-d H:i:s') . "\n";
$receipt .= "项目: 商品A\n";
$receipt .= "数量: 1\n";
$receipt .= "价格: 100元\n";
$receipt .= "================\n";
$fp = fsockopen($printer_ip, $printer_port, $errno, $errstr, 10);
if (!$fp) {
echo "无法连接到打印机: $errstr ($errno)";
} else {
fwrite($fp, $receipt);
fclose($fp);
echo "打印任务已发送";
}
?>
注意事项
- 确保打印机已正确安装并配置。
- 热敏打印机需要支持 ESC/POS 指令。
- 网络打印机需要开放对应的端口(通常是 9100)。
- 对于浏览器打印,用户需要手动点击打印按钮。






