vue前端实现打印功能
Vue 前端实现打印功能的几种方法
使用 window.print() 原生方法
通过调用浏览器原生打印 API 实现基础打印功能。创建一个隐藏的打印区域,在打印时显示内容,打印完成后隐藏。
// 在 Vue 组件中
methods: {
printContent() {
const printWindow = window.open('', '_blank')
printWindow.document.write('<html><head><title>打印</title></head><body>')
printWindow.document.write(document.getElementById('print-area').innerHTML)
printWindow.document.write('</body></html>')
printWindow.document.close()
printWindow.focus()
printWindow.print()
printWindow.close()
}
}
使用 vue-print-nb 插件
专门为 Vue 设计的打印插件,提供更便捷的打印功能集成。
安装:
npm install vue-print-nb --save
使用:
import Print from 'vue-print-nb'
Vue.use(Print)
// 模板中使用
<button v-print="'#print-area'">打印</button>
<div id="print-area">
<!-- 打印内容 -->
</div>
使用 html2canvas + jsPDF 实现 PDF 打印
将 HTML 内容先转为 canvas,再生成 PDF 进行打印,适合复杂内容的精确打印。
安装依赖:
npm install html2canvas jspdf
实现代码:
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
methods: {
async printToPDF() {
const element = document.getElementById('print-area')
const canvas = await html2canvas(element)
const imgData = canvas.toDataURL('image/png')
const pdf = new jsPDF()
pdf.addImage(imgData, 'PNG', 0, 0)
pdf.autoPrint()
window.open(pdf.output('bloburl'))
}
}
使用 CSS 控制打印样式
通过 CSS 媒体查询专门设置打印时的样式,隐藏不需要打印的元素。
@media print {
.no-print {
display: none;
}
.print-area {
width: 100%;
margin: 0;
padding: 0;
}
}
打印特定表格的实现
针对表格打印的特殊处理,确保表格完整显示不分页。
methods: {
printTable() {
const style = `
<style>
table { width: 100%; border-collapse: collapse; }
th, td { border: 1px solid #000; padding: 5px; }
@page { size: auto; margin: 0mm; }
</style>
`
const content = document.getElementById('table-to-print').outerHTML
const win = window.open('', '', 'width=800,height=600')
win.document.write(style + content)
win.document.close()
win.focus()
win.print()
}
}
打印事件监听
在打印前后执行特定操作,如显示加载状态或处理数据。
window.addEventListener('beforeprint', () => {
this.loading = true
// 打印前处理
})
window.addEventListener('afterprint', () => {
this.loading = false
// 打印后处理
})
注意事项
- 打印内容宽度不宜超过页面宽度,否则会被截断
- 背景颜色默认不打印,需设置 CSS
-webkit-print-color-adjust: exact - 分页控制可使用 CSS
page-break-before: always或page-break-after: always - 移动端打印可能存在兼容性问题,需进行充分测试
- 复杂布局建议使用 PDF 打印方案,确保跨浏览器一致性







