vue实现报表打印
Vue 实现报表打印的方法
使用 window.print() 实现基础打印
在 Vue 中可以直接调用浏览器的打印功能。创建一个隐藏的打印区域,通过 CSS 控制打印样式。
<template>
<div>
<button @click="printReport">打印报表</button>
<div id="printArea" class="print-only">
<!-- 报表内容 -->
<h1>销售报表</h1>
<table>
<!-- 表格数据 -->
</table>
</div>
</div>
</template>
<script>
export default {
methods: {
printReport() {
const printContents = document.getElementById('printArea').innerHTML;
const originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;
}
}
}
</script>
<style>
@media print {
.no-print {
display: none;
}
.print-only {
display: block;
}
}
</style>
使用 vue-print-nb 插件
vue-print-nb 是一个专门为 Vue 设计的打印插件,使用更简单。
安装插件:
npm install vue-print-nb --save
使用示例:

<template>
<div>
<button v-print="printObj">打印报表</button>
<div id="printMe">
<!-- 报表内容 -->
</div>
</div>
</template>
<script>
import print from 'vue-print-nb'
export default {
directives: {
print
},
data() {
return {
printObj: {
id: 'printMe',
popTitle: '报表打印',
extraCss: 'https://example.com/print.css'
}
}
}
}
</script>
使用 PDF 生成后打印
对于复杂报表,可先生成 PDF 再打印。使用 jsPDF 或 html2pdf 等库。
安装 html2pdf:
npm install html2pdf.js
使用示例:

<template>
<div>
<button @click="generatePDF">生成PDF并打印</button>
<div id="pdfContent">
<!-- 报表内容 -->
</div>
</div>
</template>
<script>
import html2pdf from 'html2pdf.js'
export default {
methods: {
generatePDF() {
const element = document.getElementById('pdfContent');
const opt = {
margin: 10,
filename: 'report.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
};
html2pdf().from(element).set(opt).save().then(() => {
// 打印PDF
window.print();
});
}
}
}
</script>
使用打印样式优化
通过 CSS 媒体查询专门为打印设计样式,确保打印效果符合要求。
@media print {
body {
font-size: 12pt;
color: #000;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
}
.no-print {
display: none !important;
}
@page {
size: A4;
margin: 10mm;
}
}
分页控制
对于长报表,使用 CSS 控制分页:
.page-break {
page-break-after: always;
}
在需要分页的位置添加:
<div class="page-break"></div>






