vue项目实现打印
Vue 项目中实现打印功能
在 Vue 项目中实现打印功能可以通过多种方式完成,以下是几种常见的方法:
使用 window.print() 方法
最简单的打印方式是调用浏览器的 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="printArea">
<!-- 需要打印的内容 -->
</div>
<button v-print="'#printArea'">打印</button>
</template>
使用 html2canvas 和 jsPDF 实现 PDF 打印
如果需要将内容打印为 PDF,可以使用 html2canvas 和 jsPDF 库。
安装依赖:
npm install html2canvas jspdf --save
在组件中使用:
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
methods: {
printPDF() {
html2canvas(document.querySelector('#printArea')).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF();
pdf.addImage(imgData, 'PNG', 0, 0);
pdf.save('document.pdf');
});
}
}
使用 CSS 控制打印样式
通过 CSS 的 @media print 可以控制打印时的样式,隐藏不需要打印的元素。

@media print {
.no-print {
display: none;
}
.print-only {
display: block;
}
}
使用 iframe 打印特定内容
通过动态创建 iframe 并加载需要打印的内容,可以实现更灵活的打印控制。
methods: {
printSpecificContent(content) {
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
document.body.appendChild(iframe);
const doc = iframe.contentWindow.document;
doc.open();
doc.write(content);
doc.close();
iframe.contentWindow.focus();
iframe.contentWindow.print();
document.body.removeChild(iframe);
}
}
使用第三方库 vue-html-to-paper
vue-html-to-paper 是另一个专门为 Vue 设计的打印库,支持更多自定义选项。
安装:
npm install vue-html-to-paper --save
使用:
import VueHtmlToPaper from 'vue-html-to-paper';
Vue.use(VueHtmlToPaper);
this.$htmlToPaper('printArea', {
name: '_blank',
specs: ['fullscreen=yes', 'titlebar=yes', 'scrollbars=yes'],
styles: ['/path/to/print.css']
});
以上方法可以根据具体需求选择使用,每种方法都有其适用的场景和优缺点。






