Search code examples
javascripthtmljspdfhtml2canvasmorris.js

Export Morris.js chart as PDF?


I am creating a line chart using Morris.js which the data are retrieved from MySQL database. I wanted to download it as PDF file that contains the entire chart.

I've tried using html2canvas and jsPDF to generate the PDF. However, the PDF generated/downloaded does not contain any data on it.

Here's my code:

<?php 
    $connect = mysqli_connect("localhost", "root", "", "testing");
    $query = "SELECT * FROM purchase";
    $result = mysqli_query($connect, $query);
    $chart_data = '';

    while($row = mysqli_fetch_array($result))
    {
        $chart_data .= "{ year:'".$row["year"]."', profit:".$row["profit"].", purchase:".$row["purchase"].", sale:".$row["sale"]."}, ";
    }

    $chart_data = substr($chart_data, 0, -2);
?>
<div class="row">
    <div id="chart" style="width:800px;"></div>
    <canvas id="canvas" width="800px;"></canvas>
    <button onclick="save();">Download</button>  
</div>
Morris.Line({
    element : 'chart',
    data:[<?php echo $chart_data; ?>],
    xkey:'year',
    ykeys:['profit', 'sale'],
    labels:['Profit', 'Sale'],
    hideHover:'auto',
    stacked:true
});       

function save() {
    html2canvas(document.getElementById('canvas'), {
        onrendered: function(canvas) {
            var img = canvas.toDataURL();
            var doc = new jsPDF();
            doc.addImage(img, 10, 10);
            doc.save('test.pdf');
        }
    });
}

Any ideas or advice would be greatly appreciated.


Solution

  • You don't need a canvas element as html2canvas is creating one for you.

    To make it work, I used the latest html2canvas version 1.0.0-rc.1 that uses a promise instead of a callback.

    Here is the save function:

    function save() {
        html2canvas(document.getElementById('chart')).then(canvas => {
            var w = document.getElementById("chart").offsetWidth;
            var h = document.getElementById("chart").offsetHeight;
    
            var img = canvas.toDataURL("image/jpeg", 1);
    
            var doc = new jsPDF('L', 'pt', [w, h]);
            doc.addImage(img, 'JPEG', 10, 10, w, h);
            doc.save('sample-file.pdf');
        }).catch(function(e) {
            console.log(e.message);
        });
    }
    

    A full working version: JSFiddle