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)
在组件中使用:
<template>
<div id="printContent">
<!-- 需要打印的内容 -->
</div>
<button v-print="'#printContent'">打印</button>
</template>
打印特定区域内容
通过CSS控制打印内容,可以隐藏不需要打印的部分:
@media print {
.no-print {
display: none;
}
.print-only {
display: block;
}
}
使用iframe实现打印
创建一个隐藏的iframe来加载需要打印的内容:
printWithIframe() {
const content = document.getElementById('printContent').innerHTML
const iframe = document.createElement('iframe')
iframe.style.display = 'none'
document.body.appendChild(iframe)
const frameDoc = iframe.contentDocument || iframe.contentWindow.document
frameDoc.open()
frameDoc.write(`
<html>
<head>
<title>打印内容</title>
</head>
<body>${content}</body>
</html>
`)
frameDoc.close()
setTimeout(() => {
iframe.contentWindow.focus()
iframe.contentWindow.print()
document.body.removeChild(iframe)
}, 200)
}
打印样式优化
通过CSS媒体查询优化打印效果:
@media print {
body {
margin: 0;
padding: 0;
background: white;
}
@page {
size: auto;
margin: 0mm;
}
* {
-webkit-print-color-adjust: exact !important;
color-adjust: exact !important;
}
}
打印PDF文件
如果需要打印PDF文件,可以使用pdf.js库:
printPDF(url) {
const iframe = document.createElement('iframe')
iframe.style.display = 'none'
iframe.src = url
document.body.appendChild(iframe)
iframe.onload = () => {
setTimeout(() => {
iframe.contentWindow.print()
document.body.removeChild(iframe)
}, 500)
}
}
以上方法可以根据实际需求选择使用,每种方法都有其适用场景和优缺点。







