下载依赖
npm install html2canvas
npm install jspdf
引入依赖
import html2Canvas from 'html2canvas'
import { jsPDF } from 'jspdf'
代码:
<button
@click="getPdf"
>下载PDF</button>
<div
class="report-page"
id="report-wrap"
>
页面内容........
</div>
methods :{
createImage(idName) {
return new Promise((resolve, reject) => {
const shareContent = document.getElementById(idName)
if (shareContent) {
html2Canvas(shareContent, {
dpi: 900,
scrolly: 0,
// width:eleW,//生成后的宽度
// height:eleH,//生成后的高度
scrollx: -10,
useCORS: true //允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
// backgroundColor: null //避免图片有白色边框
}).then(canvas => {
const context = canvas.getContext('2d')
context.mozImageSmoothingEnabled = false
context.webkitImageSmoothingEnabled = false
context.msImageSmoothingEnabled = false
context.imageSmoothingEnabled = false
const pageData = canvas.toDataURL('image/jpeg', 1.0)
const img = new Image()
img.src = pageData
img.onload = () => {
img.width = img.width / 5
img.height = img.height / 5
img.style.transform = 'scale(0.2)'
resolve(img)
}
})
} else {
resolve()
}
})
},
getPdf() {
Promise.all([this.createImage('report-wrap')]).then(result => {
const list = result.filter(e => !!e)
const PDF = new jsPDF('p', 'px', [list[0].width, list[0].height])
for (let index = 0; index < list.length; index++) {
const element = list[index]
PDF.addImage(element, 'JPEG', 0, 0, element.width, element.height)
if (list[index + 1]) {
PDF.addPage([list[index + 1].width, list[index + 1].height])
}
}
PDF.save('报告' + '.pdf')
})
}
}