jsPDF+html2canvas aw snap on chrome, not on firefox



我正在使用html2canvas + jsPDF编写pdf生成器。我为此使用递归方法。当我在 chrome 上启动它时,它会在第 25 次迭代中出现"Aw snap!"异常。在Mozilla上,我可以超过30,它不会崩溃。我不明白为什么。这是我的代码:

function pdfMe(){
var pdf=new jsPDF('l');
var slides=document.getElementById("diapoStock").children; //return some divs
var firstSlide=slides[0].id;
pdfSlide(firstSlide,firstSlide,pdf);
}
//PDF recursive
function pdfSlide(id,idFirst,pdf){
document.getElementById("pdfOutput").innerHTML="";   //empty the output
var next=nextElementOf(id.substr(0,id.length-3)+"Div");    //next div to PDF
showMe(id.substr(0,id.length-3));                //Show the div to PDF in 'central'
html2canvas(document.getElementById("central",{async:true})).then(function (canvas) {
document.getElementById("pdfOutput").appendChild(canvas);   //div to PDF shown
var img=canvas.toDataURL("image/png");
pdf.addImage(img, 'PNG', 0, 0, 297, 210);    //div added to PDF
if(next===idFirst){                          //if end of divs
endPDF(pdf);
}
else{
pdf.addPage();
pdfSlide(next,idFirst,pdf);             //to next div
}
});
}
//Print
function endPDF(pdf){
pdf.save('{{ propale.titre }}.pdf');
}

我不知道这是否是由于缓存大小的差异。我用console.log(window.performance.memory);打印了它,但它给了我 10 或 30 次迭代

。是由于我的递归方法吗?它是否使用了太多内存?

希望可以理解

我注意到的几件事: 每次调用 'firstSlide' 变量时,pdfMe()函数总是会覆盖它。这导致永远不去if(next === idFirst)分行。这也导致浏览器尝试一次又一次地异步转到破坏浏览器的pdfSlide()

您已将相同的 firstSlide 变量传递给pdfSlide()函数两次,但这没有什么破坏,只是不必要的。

我相信上面提到的比较是提高你表现的关键。我只是添加了一个"first"标志,只是为了向您展示我将如何保存第一项,然后开始迭代。当你到达最后一个时(我无法根据你的代码确定它(,然后尝试提出一个不同的if()语句来退出递归函数。

我知道这不会是一个复制粘贴的答案,但希望能引导您走向正确的方向。

var first = true;
var firstID = "";
function pdfMe(){
var pdf = new jsPDF('l');
var slides = document.getElementById("diapoStock").children;
if(first) firstID = slides[0].id; // creating this 'first' flag not to overwrite with every iteration
first = false;
pdfSlide(slides[0].id,firstID,pdf); // you were passing the same argument twice to the pdfSlide function. Removed one of those
};
// Added these options from the html2canvas documentation
var options = {
async: true,
allowTaint: false,
imageTimeout: 0
}
function pdfSlide(id,firstID,pdf){
document.getElementById("pdfOutput").innerHTML="";
var next = nextElementOf(id.substr(0,id.length-3)+"div"); // this needs to be set differently
showMe(id.substr(0,id.length-3));

html2canvas(document.getElementById("central",options)).then(function(canvas){
document.getElementById("pdfOutput").appendChild(canvas);
var img = canvas.toDataURL("image/png");
pdf.addImage(img, 'PNG', 0, 0, 297, 210);
if(next.id === firstID){                          // <-- this condition never happened and because of asynchronous behaviour browser tries to load the else->recursive again and again
endPDF(pdf);
}
else{
pdf.addPage();
pdfSlide(next,idFirst,pdf);
}
});
}
//Print
function endPDF(pdf){
pdf.save('{{ propale.titre }}.pdf');
}

最新更新