<template>
<div ref="pdf">123</div>
</template>
<script>
import html2canvas from 'html2canvas'
import jspdf from 'jspdf'
//install
export default {
data() {
return {
pdf: value
}
},
methods: {
downloadPdf() {
let target = this.$refs.pdf
html2canvas(target, {
useCORS: true, // 当图片是链接地址时,需加该属性,否组无法显示图片
"imageTimeout": 0,
'scale': 2,
"width": 592,
"height": 841,
})
.then(canvas => {
console.log(canvas)
let contentWidth = canvas.width; // 592px
let contentHeight = canvas.height; // 841px
let pageHeight = contentWidth / 592 * 841;
let leftHeight = contentHeight;
//页面偏移
let offsetX = 0;
let offsetY = 0;
let imgWidth = 592;
let imgHeight = 592 / 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', offsetX, offsetY, imgWidth, imgHeight)
leftHeight -= pageHeight;
offsetX -= 592;
offsetY -= 841;
//避免添加空白页
if (leftHeight > 0) {
pdf.addPage();
}
}
}
let name = '文件名.pdf'; // 定义生成的pdf的文件名字
pdf.save(name);
});
}
},
mounted() {
this.pdf = this.$refs.pdf;
},
}
</script>
<style lang="scss" scoped>
</style>