vue如何实现单据打印
Vue 实现单据打印的方法
使用浏览器原生打印 API
Vue 中可以直接调用浏览器的 window.print() 方法实现打印功能。这种方式适合打印当前页面或部分 DOM 内容。
methods: {
handlePrint() {
window.print();
}
}
打印特定区域
通过 CSS 控制打印范围,隐藏非打印内容:
@media print {
.no-print {
display: none;
}
.print-area {
display: block !important;
}
}
使用打印插件
vue-print-nb 是常用的 Vue 打印插件,支持指定打印区域和自定义样式:
安装:

npm install vue-print-nb --save
使用:
import Print from 'vue-print-nb'
Vue.use(Print);
<template>
<div id="printArea">打印内容</div>
<button v-print="'#printArea'">打印</button>
</template>
生成 PDF 打印
使用 jsPDF 或 html2pdf.js 库将内容转为 PDF 后打印:
安装:

npm install jspdf html2pdf.js
示例代码:
import html2pdf from 'html2pdf.js'
methods: {
exportPDF() {
const element = document.getElementById('print-content');
const opt = {
margin: 10,
filename: 'document.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
};
html2pdf().from(element).set(opt).save();
}
}
打印样式优化
通过 CSS 专门设置打印样式:
@media print {
body {
font-size: 12pt;
color: #000;
}
table {
width: 100%;
border-collapse: collapse;
}
@page {
size: A4;
margin: 0;
}
}
服务端打印方案
对于复杂打印需求,可将数据发送到后端生成打印文件:
axios.post('/api/print', { data: this.printData })
.then(response => {
window.open(response.data.url, '_blank');
});
注意事项
- 打印预览在不同浏览器中表现可能不一致
- 复杂表格和样式需要专门测试打印效果
- 移动端打印功能支持有限
- 考虑添加打印加载状态和错误处理
以上方法可根据具体需求选择使用,简单打印需求使用原生 API 或插件即可,复杂需求建议采用 PDF 生成方案。






