This solution allows for dynamically creating a downloadable PDF file of the current page, regardless of the size. Browsers often do not render much that is not visible to the user and this will result blank pages for larger PDFs. This solution navigates the page to ensure there is an actual render before being added to the PDF.
Export to A4 by default, matching current element display width. This means that the output is consistent with the webpage.
This can be used to capture and save complicated HTML content such as charts, images and canvas items. This could also be used for offering a frontend quote form with a download quote option which exports all of the input fields and totals.
/*
Using:
var for old iOS Safari compatibility
*/
function pdfOut(sourceElement, filename, doneEvent) {
var windowHeight = sourceElement.clientHeight;
var windowWidth = sourceElement.clientWidth;
var pageWidth = windowWidth;
var pageHeight = Math.floor(pageWidth*1.414);
var queued = 0;
var currentPage = -1;
var pdf;
queued = (windowHeight/pageHeight) + 1;
this.checkDone = function () {
if (queued < 1) {
pdf.save(filename+'.pdf');
doneEvent();
} else{
this.getPage();
}
}
this.getPage = function () {
currentPage++;
window.scrollTo(0, currentPage*pageHeight)
html2canvas(sourceElement,{width: pageWidth, height: pageHeight, y : currentPage*pageHeight}).then(canvas => {
if (pdf) {
pdf.addPage([pageWidth, pageHeight])
} else {
pdf = new jsPDF("portrait", "pt", [pageWidth, pageHeight], true);
}
pdf.addImage(canvas.toDataURL("image/png"), "PNG", 0, 0, pageWidth, pageHeight,'','FAST');
queued--;
this.checkDone();
});
}
this.getPage();
}