1、下载html2canvas、JsPDF
// 将页面html转换成图片
npm install html2canvas --save
// 将图片生成pdf
npm install jspdf --save
2、点击导出,导出内容
<template>
<div class="credit-result"
ref="result">
<div class="drawer-contenr">
<div class="result-body"
id="view">
导出内容
</div>
<div class="demo-drawer__footer">
<el-button type="primary"
:loading="loading"
@click="exportImg">{{ loading ? '导出中 ...' : '导出' }}</el-button>
</div>
</div>
</template>
<script>
import html2canvas from 'html2canvas'
import JsPDF from 'jspdf'
export default {
data () {
return {
loading: false,
title: '', // 报告名称
data: '',
}
},
created () {
this.query = this.$route.params ?? {}
},
mounted () {
this.title = '导出报告'
this.getData()
},
methods: {
// 获取数据
getData () {
let url = `/list`
this.$http.get(url).then(res => {
this.data = res
console.log(this.data)
})
},
// 导出为pdf
exportImg () {
this.loading = true;
// this.$nextTick:模块加载完成在导出,避免截图不全
this.$nextTick(() => {
this.$refs.result.scrollTop = 0; // 避免截图不全
let dom = document.getElementById('view')
new html2canvas(dom, {
useCORS: true
}).then(canvas => {
let contentWidth = canvas.width;
let contentHeight = canvas.height;
//一页pdf显示html页面生成的canvas高度;
let pageHeight = contentWidth / 592.28 * 841.89;
//未生成pdf的html页面高度
let leftHeight = contentHeight;
//页面偏移
let position = 0;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
let imgWidth = 595.28;
let imgHeight = 592.28 / contentWidth * contentHeight;
let pageData = canvas.toDataURL('image/jpeg', 1.0);
let 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', 0, position, imgWidth, imgHeight)
leftHeight -= pageHeight;
position -= 841.89;
//避免添加空白页
if (leftHeight > 0) {
pdf.addPage();
}
}
}
pdf.save(this.title + '.pdf');
this.loading = false
});
})
},
close () {
this.$emit('close')
}
}
}
</script>