vue打印功能实现
实现 Vue 打印功能的几种方法
使用 window.print() 方法
在 Vue 中可以直接调用浏览器原生打印 API。创建一个打印按钮,绑定点击事件触发 window.print()。
<template>
<button @click="printPage">打印当前页</button>
</template>
<script>
export default {
methods: {
printPage() {
window.print()
}
}
}
</script>
使用 vue-print-nb 插件
安装 vue-print-nb 插件可以更方便地实现打印功能,支持指定打印区域。
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>
使用 html2canvas 和 jsPDF 生成 PDF
对于需要将页面内容转为 PDF 再打印的场景,可以使用 html2canvas 和 jsPDF 组合。
npm install html2canvas jspdf
<template>
<div ref="content">
<!-- 需要打印的内容 -->
</div>
<button @click="exportToPDF">导出PDF并打印</button>
</template>
<script>
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
export default {
methods: {
async exportToPDF() {
const element = this.$refs.content
const canvas = await html2canvas(element)
const imgData = canvas.toDataURL('image/png')
const pdf = new jsPDF()
pdf.addImage(imgData, 'PNG', 0, 0)
pdf.autoPrint()
pdf.output('dataurlnewwindow')
}
}
}
</script>
自定义打印样式
通过 CSS 媒体查询定义打印时的样式,隐藏不需要打印的元素。
@media print {
.no-print {
display: none;
}
body {
margin: 0;
padding: 0;
}
}
打印特定表格数据
对于表格数据的打印,可以单独处理数据格式。

<template>
<button @click="printTable">打印表格</button>
</template>
<script>
export default {
data() {
return {
tableData: [...]
}
},
methods: {
printTable() {
const printWindow = window.open('', '', 'width=800,height=600')
printWindow.document.write(`
<html>
<head>
<title>表格打印</title>
<style>
table { width: 100%; border-collapse: collapse; }
th, td { border: 1px solid #000; padding: 8px; }
</style>
</head>
<body>
<table>
<thead><tr><th>标题1</th><th>标题2</th></tr></thead>
<tbody>
${this.tableData.map(row =>
`<tr><td>${row.col1}</td><td>${row.col2}</td></tr>`
).join('')}
</tbody>
</table>
</body>
</html>
`)
printWindow.document.close()
printWindow.focus()
printWindow.print()
}
}
}
</script>
注意事项
- 打印前检查页面布局,确保打印内容不会超出页面边界
- 复杂页面可能需要单独设计打印样式
- 移动端打印功能可能受限,需要测试不同浏览器兼容性
- 大量数据打印可能影响性能,建议分页处理






