vue实现发票打印
vue实现发票打印
在Vue中实现发票打印功能,通常需要结合前端打印库和样式设计。以下是实现步骤:
使用vue-print-nb插件
安装vue-print-nb插件:
npm install vue-print-nb --save
在main.js中引入并注册:
import Print from 'vue-print-nb'
Vue.use(Print)
在模板中使用:
<button v-print="printObj">打印</button>
<div id="printContent">
<!-- 发票内容 -->
</div>
在data中定义printObj:

data() {
return {
printObj: {
id: 'printContent',
popTitle: '发票打印'
}
}
}
自定义打印样式
在CSS中定义打印专用样式:
@media print {
@page {
size: A4;
margin: 0;
}
body * {
visibility: hidden;
}
#printContent, #printContent * {
visibility: visible;
}
#printContent {
position: absolute;
left: 0;
top: 0;
width: 210mm;
padding: 10mm;
box-sizing: border-box;
}
}
使用html2canvas和jsPDF实现PDF打印
安装依赖:
npm install html2canvas jspdf --save
实现方法:

import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
methods: {
async printPDF() {
const element = document.getElementById('printContent')
const canvas = await html2canvas(element, {
scale: 2,
logging: false,
useCORS: true
})
const imgData = canvas.toDataURL('image/png')
const pdf = new jsPDF('p', 'mm', 'a4')
const imgWidth = 190
const imgHeight = canvas.height * imgWidth / canvas.width
pdf.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight)
pdf.save('invoice.pdf')
}
}
发票模板设计
发票HTML结构示例:
<div id="printContent" class="invoice-template">
<div class="invoice-header">
<h2>增值税普通发票</h2>
<div class="invoice-number">发票号码:{{ invoiceNo }}</div>
</div>
<div class="invoice-body">
<table>
<tr>
<th>商品名称</th>
<th>规格</th>
<th>数量</th>
<th>单价</th>
<th>金额</th>
</tr>
<tr v-for="item in items" :key="item.id">
<td>{{ item.name }}</td>
<td>{{ item.spec }}</td>
<td>{{ item.quantity }}</td>
<td>{{ item.price }}</td>
<td>{{ item.amount }}</td>
</tr>
</table>
</div>
<div class="invoice-footer">
<div>合计金额:{{ totalAmount }}</div>
<div>开票日期:{{ invoiceDate }}</div>
</div>
</div>
注意事项
打印前确保所有动态数据已加载完成,可以在打印方法中添加数据检查逻辑
对于复杂发票样式,建议使用固定尺寸布局(如A4纸尺寸210mm×297mm)
测试不同浏览器的打印兼容性,特别是IE浏览器可能需要特殊处理
考虑添加打印预览功能,提升用户体验






