Exporting Bar Chart to PDF using Html2Canvas and jsPDF – Harshad Chopra

Exporting Bar Chart to PDF using Html2Canvas and jsPDF – Harshad Chopra

In this tutorial we will be making an app which will export bar chart to pdf using html2canvas and jsPDF . All the source code of the application is given below and copy the code and understand it and extend the app with your functionality. All the screenshots of the application is given below.

Source Code

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
  <title>Balken</title>
     <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.1.0/echarts-en.common.min.js"></script>
<!--link rel="stylesheet" href="style.css"-->

  </head>
  <body>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js"></script>
    
    <div id="body">
      <div id="chart"></div>
    </div>

         <!-- prepare a DOM container with width and height -->
    <div id="main" style="width: 750px;height:500px;"></div>
    <script type="text/javascript">
        // based on prepared DOM, initialize echarts instance
       
   </script>
<button id="exportButton" type="button">Export as PDF</button>

     </body>
</html>

script.js

var myChart = echarts.init(document.getElementById('main'));
        // specify chart configuration item and data

option = {
    color: ['#3398DB'],
    tooltip : {
        trigger: 'axis',
        axisPointer : {            
            type : 'shadow'        
        }
    },
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    xAxis : [
        {
            type : 'category',
            data : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
            axisTick: {
                alignWithLabel: true
            }
        }
    ],
    yAxis : [
        {
            type : 'value'
        }
    ],
    series : [
        {
            name:'Salami',
            type:'bar',
            barWidth: '60%',
            data:[10, 52, 200, 334, 390, 330, 220]
        }
    ]
};
        // use configuration item and data specified to show chart
        myChart.setOption(option);

$("#exportButton").click(function(){   
    html2canvas($("#main"), {
            onrendered: function(canvas) {
               var  dataURL=canvas.toDataURL('image/jpeg');
              var pdf = new jsPDF();
              pdf.addImage(dataURL, 'JPEG', 0, 0);
              pdf.save("download.pdf");
            }
        });
});

Leave a Reply

Close Menu