Exporting multi page Dash app to pdf with entire layout

Hi, I think I found something that could work as a solution. Like Arham stated, I added external js files. 3 to be precise. The first 2 are javascript libraries that I downloaded to make the 3rd (main) js file work faster. These libraries I found here https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js (saved as html2canvas.js) and https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.1/jspdf.debug.js (saved as jspdf.js)

Then I created a file called print_pdf.js with code below

function createPDF(){

var jQueryScript2 = document.createElement('script'); 
jQueryScript2.setAttribute('src','YOUR LOCAL ADDRESS HERE/assets/html2canvas.js');
document.head.appendChild(jQueryScript2);
var jQueryScript3 = document.createElement('script'); 
jQueryScript3.setAttribute('src','YOUR LOCAL ADDRESS HERE/assets/jsPDF.js');
document.head.appendChild(jQueryScript3);
	



const printArea = document.getElementById("mainContainer");

html2canvas(printArea, {scale:3}).then(function(canvas){						
	var imgData = canvas.toDataURL('image/png');
	var doc = new jsPDF('p', 'mm', "a4");
	
	const pageHeight = doc.internal.pageSize.getHeight();
	const imgWidth = doc.internal.pageSize.getWidth();
	var imgHeight = canvas.height * imgWidth / canvas.width;
	var heightLeft = imgHeight;
	
	
	var position = 10; // give some top padding to first page

	doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
	heightLeft -= pageHeight;

	while (heightLeft >= 0) {
	  position += heightLeft - imgHeight; // top padding for other pages
	  doc.addPage();
	  doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
	  heightLeft -= pageHeight;
	}
	doc.save( 'file.pdf');
	
	
})

}

setTimeout(function mainFunction(){
try {
document.getElementById(“run”).addEventListener(“click”, function(){
createPDF();
})
}
catch(err) {
console.log(err)
}
console.log(‘Listener Added!’);
}, 30000);
<

finally, adding the code (as arham indicated) in the python dash code script

html.Button(‘CREATE PDF’, id=‘run’) <

I actually was able to create a pdf - see below.

The only thing is that the code creates the pdf slowly. I think this is because it takes a while before the page understands that there is external code (in the webpage console log I see that it takes a bit before i get the message “Listener Added!”. After this message is printed the button works. Then also, the main code has a while loop to assess whether several pdf pages are required (assuming a4 pdf size).

If anybody has any suggestions speeding up this code, please share - it would be greatly appreciated.

3 Likes