vue 实现打印功能
使用 vue-print-nb 插件
安装 vue-print-nb 插件:
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>
在组件中定义 printObj:
data() {
return {
printObj: {
id: 'printContent',
popTitle: '打印标题'
}
}
}
使用 window.print() 方法
创建一个打印方法:

methods: {
handlePrint() {
window.print()
}
}
添加打印按钮:
<button @click="handlePrint">打印</button>
使用 CSS 控制打印样式:
@media print {
body * {
visibility: hidden;
}
#printArea, #printArea * {
visibility: visible;
}
#printArea {
position: absolute;
left: 0;
top: 0;
}
}
使用 iframe 实现打印
创建打印方法:

printByIframe(content) {
const iframe = document.createElement('iframe')
iframe.style.display = 'none'
document.body.appendChild(iframe)
const doc = iframe.contentWindow.document
doc.write(content)
doc.close()
iframe.contentWindow.focus()
iframe.contentWindow.print()
setTimeout(() => {
document.body.removeChild(iframe)
}, 100)
}
调用打印方法:
<button @click="printByIframe('<h1>打印内容</h1>')">打印</button>
使用 html2canvas 和 jsPDF 生成 PDF
安装依赖:
npm install html2canvas jspdf --save
创建导出方法:
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
exportPDF() {
const element = document.getElementById('printArea')
html2canvas(element).then(canvas => {
const imgData = canvas.toDataURL('image/png')
const pdf = new jsPDF()
pdf.addImage(imgData, 'PNG', 0, 0)
pdf.save('document.pdf')
})
}
添加导出按钮:
<button @click="exportPDF">导出PDF</button>
<div id="printArea">
<!-- 要导出的内容 -->
</div>






