<template>
<div class="g-down-pdf">
<div ref="pdfDom">
//插入的内容
<slot name="content" ></slot>
</div>
<div @click="savePdf" class="get-pdf">
<slot name="button">
<div>下载PDF</div>
</slot>
</div>
</div>
</template>
<script>
import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
components: {
},
props: {
},
data() {
return {
}
},
methods: {
savePdf() {
const title = '评估报告'
window.pageYOffset = 0
document.documentElement.scrollTop = 0
document.body.scrollTop = 0
const u = navigator.userAgent
const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
html2canvas(this.$refs.pdfDom, {
allowTaint: true,
y: isIOS ? 200 : 0
})
html2canvas(this.$refs.pdfDom, {allowTaint: true,y: isIOS ? 200 : 0})
.then((canvas) => {
const contentWidth = canvas.width
const contentHeight = canvas.height
const pageHeight = contentWidth / 592.28 * 841.89
let leftHeight = contentHeight
let position = 0
const imgWidth = 595.28
const imgHeight = 592.28 / contentWidth * contentHeight
const pageData = canvas.toDataURL('image/jpeg', 1.0)
const 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')
})
}
}
}
</script>
<style scoped lang="less">
.get-pdf{
width: 100vw;
height: 160px;
background: #FFFFFF;
box-shadow: 0px 2px 0px 0px #F5F5F5;
display: flex;
align-items: center;
justify-content: center;
margin-top: 40px;
&>div{
width: 90vw;
height: 100px;
background: #4475D6;
border-radius: 8px;
text-align: center;
line-height: 100px;
font-size: 36px;
font-weight: 500;
color: #FFFFFF;
}
}
</style>