vue实现预览打印
实现 Vue 打印预览功能
使用 window.print() 方法
在 Vue 中可以通过调用浏览器原生 window.print() 方法实现打印功能。创建一个专门用于打印的组件或页面,隐藏不需要打印的元素。

<template>
<div>
<button @click="handlePrint">打印</button>
<div id="printArea">
<!-- 需要打印的内容 -->
<h1>打印测试</h1>
<p>这是要打印的内容</p>
</div>
</div>
</template>
<script>
export default {
methods: {
handlePrint() {
window.print()
}
}
}
</script>
<style>
@media print {
body * {
visibility: hidden;
}
#printArea, #printArea * {
visibility: visible;
}
#printArea {
position: absolute;
left: 0;
top: 0;
}
}
</style>
使用 vue-print-nb 插件
安装 vue-print-nb 插件可以更方便地实现打印功能:

npm install vue-print-nb --save
import Print from 'vue-print-nb'
Vue.use(Print)
<template>
<div>
<button v-print="printObj">打印</button>
<div id="printContent">
<!-- 打印内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
printObj: {
id: 'printContent',
popTitle: '打印标题',
extraCss: 'https://example.com/print.css'
}
}
}
}
</script>
使用 html2canvas + jspdf 实现 PDF 导出
如果需要将页面内容导出为 PDF 再进行打印,可以使用这两个库:
npm install html2canvas jspdf --save
<template>
<div>
<button @click="exportToPDF">导出PDF</button>
<div id="pdfContent">
<!-- 要导出的内容 -->
</div>
</div>
</template>
<script>
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
export default {
methods: {
async exportToPDF() {
const element = document.getElementById('pdfContent')
const canvas = await html2canvas(element)
const imgData = canvas.toDataURL('image/png')
const pdf = new jsPDF('p', 'mm', 'a4')
const imgProps = pdf.getImageProperties(imgData)
const pdfWidth = pdf.internal.pageSize.getWidth()
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width
pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight)
pdf.save('document.pdf')
}
}
}
</script>
打印样式优化
通过 CSS 的 @media print 规则可以优化打印效果:
@media print {
/* 隐藏不需要打印的元素 */
.no-print {
display: none;
}
/* 设置打印页面大小和边距 */
@page {
size: A4;
margin: 0;
}
/* 强制分页 */
.page-break {
page-break-after: always;
}
/* 打印链接显示URL */
a[href]:after {
content: " (" attr(href) ")";
}
}
注意事项
- 打印内容应尽量使用固定单位(如pt、mm),而非相对单位(如em、rem)
- 避免在打印内容中使用背景色和背景图片,某些浏览器默认不打印背景
- 测试不同浏览器的打印效果,Chrome、Firefox 和 IE 可能有差异
- 对于复杂表格,考虑添加
page-break-inside: avoid属性防止跨页断开






