vue如何使用html2canvas和JsPDF导出pdf组件
作者:侯六六
这篇文章主要介绍了vue如何使用html2canvas和JsPDF导出pdf组件问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
使用html2canvas和JsPDF导出pdf组件
来看实例
<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
// 在ios手机上会导致 上方空白 后边内容丢失 在电脑浏览器上的ios并不会
const u = navigator.userAgent
const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1 // android终端
const isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/) // ios终端
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')
// 有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
// 当内容未超过pdf一页显示的范围,无需分页
if (leftHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
} else { // 分页
while (leftHeight > 0) {
// 在pdf.addImage(pageData, 'JPEG', 左,上,宽度,高度)设置在pdf中显示;
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;
/*position: fixed;*/
/*bottom: 0;*/
&>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>
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
