doc.save promise being executed before save
I am trying to close a tab after saving a pdf. However, the tab is closing before I get the chance to save the pdf. Is there a way to implement a synchronous callback?
here's the code:
function downloadPDF(fileName) {
html2canvas(document.body).then(function (canvas) {
// Export the canvas to its data URI representation
var imgData = canvas.toDataURL("image/jpg");
var doc = new jsPDF('l', 'pt', 'letter');
var pageWidth = doc.internal.pageSize.width;
var pageHeight = doc.internal.pageSize.height;
var imgHeight = canvas.height * pageWidth / canvas.width;
var heightRemaining = imgHeight;
var position = 0;
doc.addImage(imgData, 'JPEG', 0, position, pageWidth, imgHeight);
heightRemaining -= pageHeight;
while (heightRemaining >= 0) {
position = heightRemaining - imgHeight;
doc.addPage();
doc.addImage(imgData, 'JPEG', 0, position, pageWidth, imgHeight);
heightRemaining -= pageHeight;
}
doc.save(fileName, { returnPromise: true }).then(function(){
console.log('callback');
});
});
}
Update I also tried this (with callback being window.close()) and now the browser isn't even hitting the html2canvas .then() callback function
function downloadPDF(fileName,callback) {
html2canvas(document.body).then(function (canvas) {
// Export the canvas to its data URI representation
var imgData = canvas.toDataURL("image/jpg");
debugger;
var doc = new jsPDF('l', 'pt', 'letter');
var pageWidth = doc.internal.pageSize.width;
var pageHeight = doc.internal.pageSize.height;
var imgHeight = canvas.height * pageWidth / canvas.width;
var heightRemaining = imgHeight;
var position = 0;
doc.addImage(imgData, 'JPEG', 0, position, pageWidth, imgHeight);
heightRemaining -= pageHeight;
while (heightRemaining >= 0) {
position = heightRemaining - imgHeight;
doc.addPage();
doc.addImage(imgData, 'JPEG', 0, position, pageWidth, imgHeight);
heightRemaining -= pageHeight;
}
doc.save(fileName);
});
callback();
}
What was your solution?
@tofra Unfortunately I had a deadline and was not able to implement that part. The window closing was more of a nice to have but no luck
I have a workaround, setTimeout(()=>{ window.close() }, 500)
Your second example will not work, as callback is called directly instead of after the save is done. Have you tried await doc.save()? (just guessing)
This issue is stale because it has been open 90 days with no activity. It will be closed soon. Please comment/reopen if this issue is still relevant.
I have the same issue ... practically the same code as well... the call back is finishing before the file actually downloads
@ALOVARGAS AFAIK, there is no browser API to determine when the download has finished. I'm happy to be proven wrong.
Same issue here for a similar code.