Vue使用html2Canvas+printJS实现分页导出,打印
1.插件引入
npm i html2canvas
npm i print-js
2.使用模板
<template>
<div class="dymb">
<el-button @click="getPdf()">导出PDF</el-button>
<el-button @click="goPrint()">打印PDF</el-button>
<div class="pdfContent " id="pdfDom" ref="print">
<!-- 正面模板 -->
<div class="content marginBottom" style="page-break-after:always">
<!-- <div v-for="i in 83" :key="i">
{{i}}
</div> -->
</div>
<!-- 背面模板 -->
<div class="content content2 " style="page-break-after:always">
<!-- <div v-for="i in 83" :key="i">
{{i}}
</div> -->
</div>
</div>
</div>
</template>
<script>
import html2Canvas from 'html2Canvas'
import printJS from 'print-js'
export default {
name: 'dymb',
data () {
return {
htmlTitle: '标题',
}
},
watch: {
},
created () {
},
mounted () {
},
methods: {
goPrint () {
this.isPrint = true
html2Canvas(this.$refs.print, {
allowTaint: true,
taintTest: false,
useCORS: true,
dpi: window.devicePixelRatio * 4,
scale: 4
}).then((canvas) => {
const url = canvas.toDataURL('image/jpeg', 1.0)
printJS({
printable: url, // 要打印的id
type: 'image',
style: '@page{size:auto;margin: 1.5cm 1cm 1.5cm 1cm;}' //去除页眉页脚
})
this.isPrint = false
})
}
}
}
</script>
<style lang="scss" scoped>
// @page {
// size: auto;
// margin: 0 5px;
// }
.dymb {
width: 100%;
height: 100%;
overflow: auto;
.pdfContent {
width: 1240px;
margin: 0 auto;
box-sizing: border-box;
}
.content {
width: 1240px;
height: 1754px;
border: 1px #1c1 solid;
box-sizing: border-box;
// margin: 0 auto;
}
.content2 {
width: 1240px;
height: 1700px;
border: 1px #1c1 solid;
box-sizing: border-box;
}
.marginBottom {
margin-bottom: 30px;
}
.zm {}
.bm {}
}
</style>
3.导出方法封装
// htmlToPdf.js
// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
install (Vue, options) {
Vue.prototype.getPdf = function () {
var title = this.htmlTitle //DPF标题
html2Canvas(document.querySelector('#pdfDom'), {
allowTaint: true,
taintTest: false,
useCORS: true,
y: 1, // 对Y轴进行裁切
// width:1200,
// height:5000,
// width: 1240,
// height: 3508,
dpi: window.devicePixelRatio * 4, //将分辨率提高到特定的DPI 提高四倍
scale: 4 //按比例增加分辨率
}).then(function (canvas) {
let contentWidth = canvas.width
let contentHeight = canvas.height
let pageHeight = contentWidth / 592.28 * 841.89
let leftHeight = contentHeight
let position = 0
let imgWidth = 595.28
let imgHeight = 592.28 / contentWidth * contentHeight
let pageData = canvas.toDataURL('image/jpeg', 1.0)
let PDF = new JsPDF('', 'pt', 'a4')
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
} else {
while (leftHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight
position -= 841.89
if (leftHeight > 0) {
PDF.addPage()
}
}
}
PDF.save(title + '.pdf')
})
}
}
}
4.main.js引入
// 导出
import htmlToPdf from './utils/htmlToPDF.js'
Vue.use(htmlToPdf)
如有不足,请多指教,
未完待续,持续更新!
大家一起进步!