jsPDF Html2Canvas Project: Export Multiple Google Charts from Webpage to PDF Document in JavaScript

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');
        });
    }
}

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.