Chartjs-Is it possible to print to pdf a Canvas with other div elements?

0👍

It looks like you may need to study Javascript callbacks. The onrendered callbacks do not happen immediately, they are executed once the action is completed.

You should move the last 3 lines into the last nested onrendered callback. With this change, the PDF will be generated after the html2canvas rendering has occurred.

$('#print-chart-btn-donut').on('click', function() {

    var canvas = document.querySelector('#' + chart_name_donut + '_Chart');
    var canvas_img = canvas.toDataURL("image/png", 1.0); //JPEG will not match background color

    var doc = new jsPDF('landscape', 'in', 'letter');
    html2canvas(document.getElementById(chart_name_donut + "_Title"), {
        onrendered: function(canvas) {
            html2canvas(document.getElementById(chart_name_donut + "_LegendContainer"), {
                onrendered: function(canvas2) {
                    var img = canvas.toDataURL("image/png");

                    doc.addImage(img, 'png', -4.25, 2, 20, 4, 'Doughnut1', 0, 0);
                    var img2 = canvas2.toDataURL("image/png");
                    doc.addImage(img2, 'png', -4.25, 1.75, 20, 4, 'Doughnut2', 0, 0);

                    // Generate the PDF after the final callback has executed
                    doc.autoPrint();
                    var blob = doc.output("bloburl");
                    window.open(blob, 'Doughnut Chart', "height=" + window.outerHeight + ", width=" + 0.36 * window.innerWidth + "\"");
                }
            })
        }
    });
    doc.addImage(canvas_img, 'png', -4.25, 1.75, 20, 4, 'Doughnut', 0, 0);
});

Leave a comment