It seems that the code works but doesn’t scale too well.
It’s possible that by performing all operations in parallel, javascript’s Garbage Collection (GC) isn’t given the opportunity to clear intermediate objects, and an oversized heap causes the crash.
Performing the operations in series may have a positive effect. The code is simply derived from the code in the question.
First, an adaptor function, which promisifies html2canvas()
:
function html2canvasAsync(element) { return new Promise(function(resolve, reject) { html2canvas(element, { onrendered: function (canvas) { resolve(canvas.toDataURL('image/png')); } }); }); };
Now call divNamesForPDF.reduce(…)
to serialize the asynchronous operations and progressively add to the jsPDF doc
:
function GeneratePDFforCharts(divNamesForPDF) { if (window.Promise) { var doc = new jsPDF('l', 'mm', [297, 210], true); //true is set for pdf compression return divNamesForPDF.reduce(function(p, name, i) { return p.then(function(pageNumber) { return html2canvasAsync($(name).get(0)) // or `document.getElementById(name)` ? // return html2canvasAsync(document.getElementById(name)) // possibly? .then(function(canvas) { if (isOdd(i)) { // odds doc.addImage(canvas, 'PNG', 10, 105, 270, 100, null, 'FAST'); //x, y, width, height - FAST is used for png compression doc.text(140, 207, pageNumber.toString()); //x, y, text pageNumber++; } else { // evens if (i > 0) { doc.addPage(); } doc.addImage(canvas, 'PNG', 10, 5, 270, 100, null, 'FAST'); } return pageNumber; }).catch(function(e) { // Error handling is a good idea console.log(e); doc.text(35, 25, e.message); // possibly add the error message to doc }); }); }, Promise.resolve(1)) // starter promise resolved with page number 1 .then(function() { doc.save('IEA_Global_MonthlyStocks_Analytics.pdf'); }); } }
We evaluated the performance of Llama 3.1 vs GPT-4 models on over 150 benchmark datasets…
The manufacturing industry is undergoing a significant transformation with the advent of Industrial IoT Solutions.…
If you're reading this, you must have heard the buzz about ChatGPT and its incredible…
How to Use ChatGPT in Cybersecurity If you're a cybersecurity geek, you've probably heard about…
Introduction In the dynamic world of cryptocurrencies, staying informed about the latest market trends is…
The Events Calendar Widgets for Elementor has become easiest solution for managing events on WordPress…