npm install html2canvas
npm install jspdf
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
handleDownloadPdf() {
let _this = this;
//----此处是解决页面带滚动条的时候截图不全问题
window.pageYoffset = 0;
document.documentElement.scrollTop = 0;
document.body.scrollTop = 0;
let canvas = document.createElement("canvas");
let context = canvas.getContext("2d");
let _articleHtml = document.getElementById('imageTofile');
let _w = _articleHtml.clientWidth;
let _h = _articleHtml.clientHeight;
console.log('clientWidth', _w, 'clientHeight', _h)
//-----这里解决生成的pdf不清晰的问题 先放大3倍----后面再缩小3倍
let scale = 3;
canvas.width = _w * scale;
canvas.height = _h * scale;
context.scale(scale, scale);
let opts = {scale: 1, width: _w, height: _h, canvas: canvas, useCORS: true};
(window.html2canvas || html2canvas)(_articleHtml, opts).then(canvas => {
//IOS13.4无效解决 和{(intermediate value)(intermediate value)} is not a function+;
_this.createPdfAll(canvas, scale);
});
},
createPdfAll (canvas, scale) {//生成图片->pdf
let that = this
//-----------宽高缩小3倍 解决失真---------------------
let contentWidth = canvas.width / scale
let contentHeight = canvas.height / scale
let pdf = new jsPDF('', 'pt', [contentWidth, contentHeight<contentWidth?contentWidth:contentHeight]) //此处加50是pdf最后离底部的空白距离。根据需要自行调节 页面节点宽高比最小1:1,否则图片会变形
let pageData = canvas.toDataURL('image/jpeg', 1.0);
let img = new Image();
img.src = pageData;
img.onload = function () {//确定图片加载成功以后再插入到pdf,有用户反馈 pdf里面的文件是 完 全空白的,怀疑是图片未加载就执行了将图片插入到pdf的操作
//这里只生成了一页的pdf,并未截断,需要截断的话在此处操作
pdf.addImage(pageData, 'JPEG', 0, 0, contentWidth, contentHeight)
//这里是将pdf的流文件---》file文件
let filename = '数据看板.pdf';
let dataURL = pdf.output('dataurlstring');
//--base64--->blob--->file 无兼容问题
let blob = that.dataURLtoBlob(dataURL);
let file = that.blobToFile(blob, filename)
that.downloadFile(file, filename)
}
},
dataURLtoBlob(dataURL) {
const arr = dataURL.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const bStr = atob(arr[1]);
let n = bStr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bStr.charCodeAt(n);
}
return new Blob([u8arr], { type: mime });
},
blobToFile(theBlob, fileName) {
return new window.File([theBlob], `${fileName}.pdf`, { type: 'application/pdf' })
},