前人的基础上稍加修改优化了一下,解决了html2Canvas只能截取可见html部分问题以及截取全部目标内容后样式失效问题。
具体问题需要具体分析。
exportPDF(){//点击事件
//imageDom为pdf目标,注意imageDom的样式需要和body平级,注意不要污染全局
var width = this.$refs.imageDom.style.width
var cloneDom = this.$refs.imageDom.cloneNode(true)
cloneDom.style.width = width
document.body.appendChild(cloneDom)
html2Canvas(cloneDom,{
allowTain:true
}).then(function(canvas){
let contentWidth = canvas.width;
let contentHeight = canvas.height;
let pageHeight = contentWidth / 592.28 * 841.89;
let leftHeight = contentHeight;
let position = 0;
let imgWidth = 592.28;
let imgHeight = 592.28 / contentWidth * contentHeight;
let pageData = canvas.toDataURL('image/jpej',1.0);
let 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('可以设置成变量.pdf')
})
document.body.removeChild(cloneDom)
}
但是还有别的问题:html连续的内容被粗暴截断,后续继续更新,先把基本功能实现