vue实现发票打印
Vue 实现发票打印方案
在 Vue 中实现发票打印功能通常需要结合浏览器打印 API 和样式控制。以下是几种常见实现方式:
方案一:使用 window.print() 原生打印
创建独立的发票打印组件,通过 CSS 控制打印样式:
<template>
<div class="invoice-print">
<button @click="printInvoice">打印发票</button>
<div class="invoice-content" ref="invoiceContent">
<!-- 发票内容结构 -->
<h3>发票抬头</h3>
<table>
<!-- 表格内容 -->
</table>
</div>
</div>
</template>
<script>
export default {
methods: {
printInvoice() {
const printContent = this.$refs.invoiceContent.innerHTML;
const originalContent = document.body.innerHTML;
document.body.innerHTML = printContent;
window.print();
document.body.innerHTML = originalContent;
}
}
}
</script>
<style>
@media print {
body * {
visibility: hidden;
}
.invoice-content, .invoice-content * {
visibility: visible;
}
.invoice-content {
position: absolute;
left: 0;
top: 0;
width: 100%;
}
}
</style>
方案二:使用 html2canvas + jsPDF 生成 PDF
适用于需要精确控制打印格式或生成 PDF 文件的场景:
npm install html2canvas jspdf
组件实现:

<template>
<div>
<button @click="exportToPDF">导出PDF</button>
<div id="invoiceTemplate">
<!-- 发票模板 -->
</div>
</div>
</template>
<script>
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
export default {
methods: {
async exportToPDF() {
const element = document.getElementById('invoiceTemplate');
const canvas = await html2canvas(element, {
scale: 2,
logging: false,
useCORS: true
});
const pdf = new jsPDF('p', 'mm', 'a4');
const imgData = canvas.toDataURL('image/png');
const imgWidth = 210; // A4宽度
const imgHeight = canvas.height * imgWidth / canvas.width;
pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
pdf.save('invoice.pdf');
}
}
}
</script>
方案三:使用专用打印插件
对于复杂打印需求,可以考虑专用打印库:
npm install vue-print-nb
使用示例:

import Print from 'vue-print-nb';
Vue.use(Print);
<template>
<div>
<button v-print="printObj">打印</button>
<div id="printContent">
<!-- 打印内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
printObj: {
id: 'printContent',
popTitle: '发票打印',
extraCss: 'https://example.com/print.css'
}
}
}
}
</script>
关键注意事项
打印样式必须通过 @media print 专门定义,普通样式在打印时可能无效。建议设置:
@media print {
@page {
size: A4 portrait;
margin: 0;
}
body {
-webkit-print-color-adjust: exact;
}
.no-print {
display: none !important;
}
}
对于中国发票特有的需求,如发票号码、二维码、印章等,需要特别注意:
- 使用固定定位确保元素位置精确
- 二维码建议使用 canvas 绘制
- 印章可以使用透明 PNG 叠加
响应式打印处理
针对不同尺寸纸张的适配方案:
function getPrintStyle(pageSize = 'A4') {
const sizes = {
'A4': { width: '210mm', height: '297mm' },
'A5': { width: '148mm', height: '210mm' }
};
return `
@page {
size: ${sizes[pageSize].width} ${sizes[pageSize].height};
margin: 10mm;
}
`;
}
以上方案可根据具体业务需求组合使用,建议先进行打印预览测试,确保各浏览器兼容性。






