vue实现打印票据
Vue 实现打印票据的方法
使用 window.print() 方法
在 Vue 项目中,可以直接调用浏览器的打印功能。创建一个打印按钮,点击时触发打印当前页面或指定区域。
<template>
<div>
<div id="printArea">
<!-- 票据内容 -->
<h1>票据标题</h1>
<p>票据详情...</p>
</div>
<button @click="print">打印票据</button>
</div>
</template>
<script>
export default {
methods: {
print() {
window.print();
}
}
};
</script>
<style>
@media print {
body * {
visibility: hidden;
}
#printArea, #printArea * {
visibility: visible;
}
#printArea {
position: absolute;
left: 0;
top: 0;
}
}
</style>
使用第三方库 vue-print-nb
vue-print-nb 是一个专门为 Vue 设计的打印插件,支持打印指定区域。
安装:

npm install vue-print-nb --save
使用:
<template>
<div>
<div id="printArea">
<!-- 票据内容 -->
<h1>票据标题</h1>
<p>票据详情...</p>
</div>
<button v-print="printObj">打印票据</button>
</div>
</template>
<script>
export default {
data() {
return {
printObj: {
id: 'printArea',
popTitle: '票据打印'
}
};
}
};
</script>
使用 html2canvas 和 jsPDF
如果需要将票据内容导出为 PDF 再打印,可以使用 html2canvas 和 jsPDF 组合。

安装:
npm install html2canvas jspdf --save
使用:
<template>
<div>
<div id="printArea">
<!-- 票据内容 -->
<h1>票据标题</h1>
<p>票据详情...</p>
</div>
<button @click="exportToPDF">导出为PDF并打印</button>
</div>
</template>
<script>
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
export default {
methods: {
async exportToPDF() {
const element = document.getElementById('printArea');
const canvas = await html2canvas(element);
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF();
pdf.addImage(imgData, 'PNG', 0, 0);
pdf.save('票据.pdf');
// 如果需要直接打印
// pdf.autoPrint();
// window.open(pdf.output('bloburl'), '_blank');
}
}
};
</script>
打印样式优化
为了确保打印效果符合票据要求,可以通过 CSS 的 @media print 规则优化打印样式。
@media print {
@page {
size: auto; /* 自动尺寸 */
margin: 0mm; /* 无外边距 */
}
body {
padding: 10mm;
font-family: Arial, sans-serif;
}
.no-print {
display: none !important;
}
}
注意事项
- 票据内容通常需要固定宽度,避免打印时内容被截断。
- 测试不同浏览器的打印效果,确保兼容性。
- 对于复杂的票据布局,建议使用表格或 Flexbox 布局。






