vue页面实现打印功能
使用 window.print() 方法
在 Vue 组件中直接调用浏览器原生打印 API,适合简单打印需求。通过 window.print() 触发浏览器打印对话框。
<template>
<div>
<div id="printContent">
<!-- 需要打印的内容 -->
<h1>打印标题</h1>
<p>打印内容示例</p>
</div>
<button @click="handlePrint">打印</button>
</div>
</template>
<script>
export default {
methods: {
handlePrint() {
window.print();
}
}
}
</script>
<style>
@media print {
/* 隐藏非打印内容 */
body * {
visibility: hidden;
}
#printContent, #printContent * {
visibility: visible;
}
/* 调整打印布局 */
#printContent {
position: absolute;
left: 0;
top: 0;
}
}
</style>
使用 vue-print-nb 插件
安装第三方插件 vue-print-nb 提供更便捷的打印功能,支持指定打印区域和自定义配置。
npm install vue-print-nb --save
在 Vue 项目中注册插件:
import Print from 'vue-print-nb'
Vue.use(Print)
组件中使用方式:
<template>
<div>
<div id="printArea">
<!-- 打印内容 -->
<table>
<tr><th>名称</th><th>值</th></tr>
<tr><td>项目</td><td>示例</td></tr>
</table>
</div>
<button v-print="printConfig">打印表格</button>
</div>
</template>
<script>
export default {
data() {
return {
printConfig: {
id: 'printArea',
popTitle: '打印标题', // 打印页眉
extraCss: 'https://example.com/print.css', // 额外CSS
extraHead: '<meta http-equiv="Content-Language" content="zh-cn">' // 额外HEAD
}
}
}
}
</script>
使用 html2canvas + jsPDF 生成PDF打印
需要先安装依赖库:
npm install html2canvas jspdf --save
实现代码示例:
<template>
<div>
<div ref="printRef">
<!-- 复杂打印内容 -->
<div v-for="item in list" :key="item.id">
{{ item.name }}: {{ item.value }}
</div>
</div>
<button @click="exportToPDF">导出PDF并打印</button>
</div>
</template>
<script>
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
export default {
data() {
return {
list: [
{ id: 1, name: '项目A', value: 100 },
{ id: 2, name: '项目B', value: 200 }
]
}
},
methods: {
async exportToPDF() {
const element = this.$refs.printRef
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 pageHeight = 297 // A4纸高度
const imgHeight = canvas.height * imgWidth / canvas.width
let heightLeft = imgHeight
let position = 0
pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
heightLeft -= pageHeight
while (heightLeft >= 0) {
position = heightLeft - imgHeight
pdf.addPage()
pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
heightLeft -= pageHeight
}
pdf.save('report.pdf')
// 如需直接打印
// pdf.autoPrint()
// window.open(pdf.output('bloburl'))
}
}
}
</script>
打印样式优化技巧
为获得更好的打印效果,需要在 CSS 中设置打印专用样式:
@media print {
/* 隐藏不需要打印的元素 */
.no-print {
display: none !important;
}
/* 确保链接显示完整URL */
a[href^="http"]:after {
content: " (" attr(href) ")";
}
/* 分页控制 */
.page-break {
page-break-after: always;
}
/* 背景颜色和图像 */
* {
-webkit-print-color-adjust: exact !important;
print-color-adjust: exact !important;
}
/* 调整边距 */
@page {
size: auto;
margin: 10mm;
}
}
服务端打印方案
对于需要精确控制打印格式的场景,可考虑服务端生成打印文档:
// 后端API示例(Node.js)
const express = require('express')
const puppeteer = require('puppeteer')
const app = express()
app.get('/print', async (req, res) => {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto('http://your-frontend-url/print-view')
const pdf = await page.pdf({
format: 'A4',
printBackground: true,
margin: { top: '20mm', right: '20mm', bottom: '20mm', left: '20mm' }
})
await browser.close()
res.contentType('application/pdf')
res.send(pdf)
})
前端调用方式:
this.$axios.get('/print', { responseType: 'blob' })
.then(response => {
const blob = new Blob([response.data], { type: 'application/pdf' })
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = 'document.pdf'
link.click()
})






