vue实现打印和预览
Vue 实现打印功能
使用 window.print() 方法结合 CSS 控制打印样式是最基础的打印方案。Vue 中可以封装为组件或方法。
安装打印依赖库(可选):
npm install vue-print-nb
注册插件(全局):
import Print from 'vue-print-nb'
Vue.use(Print)
模板中使用指令:
<button v-print="'#printArea'">打印</button>
<div id="printArea">
<!-- 需要打印的内容 -->
</div>
自定义打印样式:
@media print {
body * {
visibility: hidden;
}
#printArea, #printArea * {
visibility: visible;
}
#printArea {
position: absolute;
left: 0;
top: 0;
}
}
Vue 实现预览功能
使用 iframe 或 PDF 预览库实现内容预览。

安装 PDF 预览库:
npm install vue-pdf
组件中使用 PDF 预览:
<template>
<pdf :src="pdfUrl" style="width: 100%; height: 800px;"></pdf>
</template>
<script>
import pdf from 'vue-pdf'
export default {
components: { pdf },
data() {
return {
pdfUrl: '/example.pdf'
}
}
}
</script>
HTML 内容预览方案:

<div class="preview-container" v-html="previewContent"></div>
<style>
.preview-container {
border: 1px solid #eee;
padding: 20px;
background: white;
box-shadow: 0 0 10px rgba(0,0,0,0.1);
}
</style>
打印与预览组合实现
创建可复用组件:
<template>
<div>
<button @click="showPreview">预览</button>
<button v-print="printConfig">打印</button>
<div v-if="isPreviewVisible" class="preview-modal">
<div class="preview-content" id="printContent">
<!-- 动态插槽内容 -->
<slot></slot>
</div>
<button @click="hidePreview">关闭</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
isPreviewVisible: false,
printConfig: {
id: 'printContent',
popTitle: '文档打印',
extraCss: 'https://example.com/print.css'
}
}
},
methods: {
showPreview() {
this.isPreviewVisible = true
},
hidePreview() {
this.isPreviewVisible = false
}
}
}
</script>
<style>
.preview-modal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.preview-content {
background: white;
padding: 20px;
max-width: 80%;
max-height: 80vh;
overflow: auto;
}
</style>
高级打印控制
分页打印控制:
@media print {
.page-break {
page-break-after: always;
}
}
打印事件监听:
window.addEventListener('beforeprint', () => {
console.log('打印前触发')
})
window.addEventListener('afterprint', () => {
console.log('打印后触发')
})
打印参数配置示例:
const printSettings = {
silent: false,
styles: [
'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'
],
timeout: 1000,
debug: false
}






