vue实现打印功能
使用 window.print() 方法
在 Vue 中实现打印功能可以直接调用浏览器原生的 window.print() 方法。这种方法适用于打印整个页面或当前可见区域。
methods: {
printPage() {
window.print();
}
}
使用 vue-print-nb 插件
vue-print-nb 是一个专门为 Vue 开发的打印插件,支持局部打印和自定义样式。
安装插件:
npm install vue-print-nb --save
在 main.js 中引入并使用:
import Print from 'vue-print-nb'
Vue.use(Print)
在模板中使用:
<button v-print="printObj">打印</button>
<div id="printContent">
<!-- 需要打印的内容 -->
</div>
<script>
export default {
data() {
return {
printObj: {
id: 'printContent',
popTitle: '打印标题'
}
}
}
}
</script>
使用 html2canvas 和 jsPDF 实现 PDF 打印
这种方法可以将 HTML 内容转换为图片,再生成 PDF 进行打印。
安装依赖:
npm install html2canvas jspdf --save
实现代码:
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
methods: {
async printPDF() {
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('document.pdf')
}
}
打印特定区域并隐藏其他内容
可以通过 CSS 控制打印时显示和隐藏的内容。
@media print {
body * {
visibility: hidden;
}
#printArea, #printArea * {
visibility: visible;
}
#printArea {
position: absolute;
left: 0;
top: 0;
}
}
自定义打印样式
可以为打印页面单独设置样式,通过 @media print 规则实现。
@media print {
@page {
size: A4;
margin: 0;
}
body {
font-size: 12pt;
}
.no-print {
display: none !important;
}
}
注意事项
浏览器打印功能可能在不同浏览器中有差异,建议在多个浏览器中测试。
打印前确保内容已完全加载,特别是包含动态数据的情况。

对于复杂的打印需求,可能需要使用专门的打印服务或后端生成 PDF。






