vue实现小票打印代码
使用Vue实现小票打印功能
在Vue中实现小票打印功能,可以通过浏览器打印API或第三方库来实现。以下是两种常见的方法:

方法一:使用浏览器打印API
创建一个Vue组件,用于展示小票内容,并调用浏览器的打印功能。

<template>
<div>
<button @click="printReceipt">打印小票</button>
<div id="receipt" ref="receipt">
<h3>购物小票</h3>
<p>订单号: {{ orderId }}</p>
<p>日期: {{ currentDate }}</p>
<table>
<tr>
<th>商品</th>
<th>数量</th>
<th>价格</th>
</tr>
<tr v-for="(item, index) in items" :key="index">
<td>{{ item.name }}</td>
<td>{{ item.quantity }}</td>
<td>{{ item.price }}</td>
</tr>
</table>
<p>总计: {{ total }}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {
orderId: '123456',
currentDate: new Date().toLocaleString(),
items: [
{ name: '商品A', quantity: 2, price: 10 },
{ name: '商品B', quantity: 1, price: 20 }
]
}
},
computed: {
total() {
return this.items.reduce((sum, item) => sum + (item.price * item.quantity), 0)
}
},
methods: {
printReceipt() {
const printContent = this.$refs.receipt.innerHTML
const originalContent = document.body.innerHTML
document.body.innerHTML = printContent
window.print()
document.body.innerHTML = originalContent
}
}
}
</script>
<style>
@media print {
body * {
visibility: hidden;
}
#receipt, #receipt * {
visibility: visible;
}
#receipt {
position: absolute;
left: 0;
top: 0;
width: 80mm;
}
}
</style>
方法二:使用html2canvas和jsPDF库
对于需要更复杂打印需求或生成PDF的情况,可以结合html2canvas和jsPDF库。
<template>
<div>
<button @click="printPDF">打印为PDF</button>
<div id="receipt" ref="receipt">
<!-- 小票内容同上 -->
</div>
</div>
</template>
<script>
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
export default {
methods: {
async printPDF() {
const element = this.$refs.receipt
const canvas = await html2canvas(element, {
scale: 2,
logging: false,
useCORS: true
})
const imgData = canvas.toDataURL('image/png')
const pdf = new jsPDF({
orientation: 'portrait',
unit: 'mm',
format: [80, 200] // 小票常用尺寸
})
pdf.addImage(imgData, 'PNG', 0, 0, 80, 0)
pdf.save('receipt.pdf')
}
}
}
</script>
方法三:使用热敏打印机(ESC/POS指令)
如果需要连接热敏打印机,可以使用串口或网络打印。
// 安装serialport库
npm install serialport
// Vue组件中使用
import { SerialPort } from 'serialport'
methods: {
async printToThermalPrinter() {
const port = new SerialPort({
path: 'COM3', // 打印机端口
baudRate: 19200
})
const commands = [
'\x1B\x40', // 初始化
'\x1B\x21\x08', // 设置字体
'购物小票\n\n',
'订单号: 123456\n',
'日期: ' + new Date().toLocaleString() + '\n\n',
'\x1B\x45\x01', // 加粗
'商品 数量 价格\n',
'\x1B\x45\x00', // 取消加粗
'商品A 2 20\n',
'商品B 1 20\n\n',
'总计: 40\n\n',
'\x1D\x56\x41\x03' // 切纸
]
port.write(Buffer.from(commands.join('')), (err) => {
if (err) console.error('打印错误:', err)
port.close()
})
}
}
注意事项
- 浏览器打印API在不同浏览器中表现可能不一致,建议测试多种浏览器
- 小票样式应使用固定宽度(通常80mm),并设置合适的字体大小
- 热敏打印机需要安装对应驱动,并确保连接正确
- 对于网络打印机,可能需要使用WebSocket或HTTP API进行通信
以上方法可根据实际需求选择使用,浏览器打印适合简单场景,PDF打印适合需要保存的场景,热敏打印机适合实体店使用。






