vue实现打印模板
Vue 实现打印模板的方法
使用 window.print() 方法
在 Vue 中可以通过调用浏览器原生的 window.print() 方法实现打印功能。创建一个隐藏的打印区域,将需要打印的内容放入其中,调用打印时只显示该区域。
<template>
<div>
<button @click="print">打印</button>
<div class="print-area" ref="printArea">
<!-- 打印内容 -->
<h1>打印模板</h1>
<p>这里是需要打印的内容</p>
</div>
</div>
</template>
<script>
export default {
methods: {
print() {
const printArea = this.$refs.printArea;
const printWindow = window.open('', '', 'width=800,height=600');
printWindow.document.write(printArea.innerHTML);
printWindow.document.close();
printWindow.focus();
printWindow.print();
printWindow.close();
}
}
};
</script>
<style>
@media print {
body * {
visibility: hidden;
}
.print-area, .print-area * {
visibility: visible;
}
.print-area {
position: absolute;
left: 0;
top: 0;
}
}
</style>
使用第三方库 vue-print-nb
vue-print-nb 是一个专门为 Vue 设计的打印插件,使用简单方便。
安装:
npm install vue-print-nb --save
使用:
<template>
<div>
<button v-print="printObj">打印</button>
<div id="printContent">
<!-- 打印内容 -->
<h1>打印模板</h1>
<p>使用 vue-print-nb 打印的内容</p>
</div>
</div>
</template>
<script>
import print from 'vue-print-nb'
export default {
directives: {
print
},
data() {
return {
printObj: {
id: 'printContent',
popTitle: '打印标题'
}
}
}
}
</script>
使用 CSS 控制打印样式
通过 CSS 的 @media print 可以专门设置打印时的样式,隐藏不需要打印的元素,调整打印布局。
@media print {
.no-print {
display: none;
}
.print-only {
display: block;
}
body {
font-size: 12pt;
color: #000;
}
}
动态生成打印内容
对于需要动态生成的打印内容,可以使用 Vue 的数据绑定和计算属性来生成打印模板。
<template>
<div>
<button @click="printDynamic">打印动态内容</button>
<div ref="dynamicPrintArea">
<h1>{{ title }}</h1>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data() {
return {
title: '动态打印内容',
items: [
{ id: 1, name: '项目1' },
{ id: 2, name: '项目2' }
]
}
},
methods: {
printDynamic() {
const printWindow = window.open('', '', 'width=800,height=600');
printWindow.document.write(`
<html>
<head>
<title>打印预览</title>
<style>
body { font-family: Arial; }
h1 { color: #333; }
ul { list-style: none; }
</style>
</head>
<body>
${this.$refs.dynamicPrintArea.innerHTML}
</body>
</html>
`);
printWindow.document.close();
printWindow.print();
}
}
}
</script>
打印 PDF 文件
如果需要生成 PDF 而非直接打印,可以使用 jsPDF 或 html2pdf 等库。
安装 html2pdf:
npm install html2pdf.js
使用:
<template>
<div>
<button @click="exportToPDF">导出PDF</button>
<div id="pdfContent">
<!-- PDF内容 -->
<h1>PDF模板</h1>
<p>将内容导出为PDF文件</p>
</div>
</div>
</template>
<script>
import html2pdf from 'html2pdf.js'
export default {
methods: {
exportToPDF() {
const element = document.getElementById('pdfContent');
const opt = {
margin: 10,
filename: 'document.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2 },
jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' }
};
html2pdf().from(element).set(opt).save();
}
}
}
</script>
以上方法可以根据具体需求选择使用,简单打印需求可使用原生方法,复杂需求可借助第三方库实现更专业的打印效果。







