用Python编程实现小票生成与打印
在日常的商业运营中,小票(收据)的生成和打印是非常常见的需求。使用Python编程语言,我们可以轻松地实现小票的格式化生成,甚至结合热敏打印机的API实现自动化打印。本文将从基础的小票文本格式化、面向对象的小票生成器,到连接实际硬件打印,逐步教你如何用Python编程实现小票功能。
一、基础文本小票的格式化
小票通常具有以下特点:标题居中、分隔线、商品列表左对齐且金额右对齐、以及总计加粗显示。我们可以利用Python的字符串内置方法(如center()、ljust()、rjust())来实现这种排版。
以下是一个基础的小票生成代码示例:
def generate_simple_receipt():
store_name = "www.ipipp.com Store"
items = [
("Apple", 2, 3.5),
("Banana", 3, 2.0),
("Orange", 1, 5.0),
]
width = 32 # 假设小票宽度为32个字符
receipt_lines = []
# 标题居中
receipt_lines.append(store_name.center(width))
receipt_lines.append("=" * width)
# 表头
receipt_lines.append(f"{'Item':5}{'Price':>12}")
receipt_lines.append("-" * width)
# 商品列表
total = 0
for name, qty, price in items:
line_total = qty * price
total += line_total
# 商品名左对齐,数量居右,金额居右保留两位小数
receipt_lines.append(f"{name:5}{line_total:>12.2f}")
# 总计
receipt_lines.append("-" * width)
receipt_lines.append(f"{'Total':12.2f}")
receipt_lines.append("=" * width)
return "n".join(receipt_lines)
if __name__ == "__main__":
print(generate_simple_receipt())二、面向对象的小票生成器
在实际应用中,商品数据往往是动态的。为了提高代码的复用性和可维护性,我们可以将小票生成逻辑封装成一个类。
class ReceiptGenerator:
def __init__(self, store_name="www.ipipp.com Store", width=32):
self.store_name = store_name
self.width = width
self.items = []
def add_item(self, name, quantity, price):
"""添加商品到小票"""
self.items.append({
"name": name,
"qty": quantity,
"price": price
})
def generate(self):
"""生成格式化的小票字符串"""
lines = []
lines.append(self.store_name.center(self.width))
lines.append("=" * self.width)
lines.append(f"{'Item':6}{'Amount':>14}")
lines.append("-" * self.width)
total_amount = 0
for item in self.items:
amount = item["qty"] * item["price"]
total_amount += amount
lines.append(f"{item['name']:6}{amount:>14.2f}")
lines.append("-" * self.width)
lines.append(f"{'TOTAL':14.2f}")
lines.append("=" * self.width)
lines.append("Thank you for shopping!".center(self.width))
return "n".join(lines)
# 使用示例
if __name__ == "__main__":
receipt = ReceiptGenerator()
receipt.add_item("Laptop", 1, 5999.00)
receipt.add_item("Mouse", 2, 49.50)
receipt.add_item("Keyboard", 1, 199.00)
print(receipt.generate())三、连接热敏打印机输出
如果需要将生成的小票直接发送到热敏打印机,我们可以使用python-escpos库。这是一个非常强大的Python库,支持通过USB、串口或网络连接ESC/POS兼容的打印机。
首先,你需要安装该库:
pip install python-escpos
以下是通过USB连接打印机并打印小票的示例代码:
from escpos.printer import Usb
def print_receipt_via_usb():
"""通过USB连接热敏打印机打印小票"""
# 请根据实际打印机的Vendor ID和Product ID进行修改
# 可以在终端输入 lsusb 命令查看 (Linux/Mac)
p = Usb(0x0416, 0x5011)
# 生成小票内容对象
receipt = ReceiptGenerator(store_name="www.ipipp.com")
receipt.add_item("Coffee", 2, 15.0)
receipt.add_item("Tea", 1, 10.0)
# 设置居中对齐打印标题
p.set(align='center')
p.text("www.ipipp.com Storen")
p.text("========================n")
# 设置左对齐打印商品列表
p.set(align='left')
for item in receipt.items:
amount = item['qty'] * item['price']
line_text = f"{item['name']:3} {amount:>10.2f}n"
p.text(line_text)
p.text("------------------------n")
# 计算并打印总计
total = sum(i['qty'] * i['price'] for i in receipt.items)
p.set(align='right')
p.text(f"TOTAL: {total:.2f}n")
p.text("========================n")
# 切纸
p.cut()
if __name__ == "__main__":
print_receipt_via_usb()四、总结
通过Python编程生成小票并不复杂。核心在于理解小票的排版规则并熟练运用字符串格式化方法。对于更进阶的需求,如直接控制硬件打印机,借助python-escpos等第三方库可以大大简化开发流程。无论是用于POS系统开发,还是个人项目的自动化收据处理,Python都能提供高效且优雅的解决方案。