vue实现模板打印
使用vue-print-nb插件实现打印
安装vue-print-nb插件
npm install vue-print-nb --save
在main.js中引入并注册插件
import Print from 'vue-print-nb'
Vue.use(Print)
在组件中使用v-print指令
<template>
<div>
<button v-print="printObj">打印</button>
<div id="printContent">
<!-- 需要打印的内容 -->
</div>
</div>
</template>
<script>
export default {
data() {
return {
printObj: {
id: 'printContent',
popTitle: '打印标题'
}
}
}
}
</script>
使用window.print()原生方法
创建打印样式
@media print {
body * {
visibility: hidden;
}
#printArea, #printArea * {
visibility: visible;
}
#printArea {
position: absolute;
left: 0;
top: 0;
}
}
实现打印方法
methods: {
print() {
const printContent = document.getElementById('printArea').innerHTML
const originalContent = document.body.innerHTML
document.body.innerHTML = printContent
window.print()
document.body.innerHTML = originalContent
}
}
使用html2canvas+jspdf实现PDF导出
安装依赖
npm install html2canvas jspdf --save
实现PDF导出
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'
methods: {
exportPDF() {
const element = document.getElementById('pdfContent')
html2canvas(element).then(canvas => {
const imgData = canvas.toDataURL('image/png')
const pdf = new jsPDF('p', 'mm', 'a4')
const imgWidth = 210
const pageHeight = 295
const imgHeight = canvas.height * imgWidth / canvas.width
let heightLeft = imgHeight
let position = 0
pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
heightLeft -= pageHeight
while (heightLeft >= 0) {
position = heightLeft - imgHeight
pdf.addPage()
pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight)
heightLeft -= pageHeight
}
pdf.save('document.pdf')
})
}
}
使用Vue插件vue-html-to-paper
安装插件
npm install vue-html-to-paper
配置和使用
import VueHtmlToPaper from 'vue-html-to-paper'
Vue.use(VueHtmlToPaper)
methods: {
print() {
this.$htmlToPaper('printContent', {
name: '_blank',
specs: ['fullscreen=yes','titlebar=yes','scrollbars=yes'],
styles: ['/path/to/print.css']
})
}
}






