jsPDF Html2Canvas Library Tutorial to Export Colorful Barcharts to PDF Document Using CanvasJS in Javascript Full Project For Beginners

 

 

Welcome folks today in this blog post we will be exporting multiple barcharts to pdf document in javascript using canvasjs library. All the full source code of the application is shown below.

 

 

 

Get Started

 

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

 

index.html

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    
  <button id="exportButton" type="button">Export as PDF</button>
  <div id="chartsContainer">
    <div id="chartContainer1" style="height: 300px; width: 100%;"></div>
    <div id="chartContainer2" style="height: 300px; width: 100%;"></div>
  </div>
    
    
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.7.0/canvasjs.min.js"></script>
<script>
var chart1 = new CanvasJS.Chart("chartContainer1", {
    title: {
    text: "Column Chart"
  },
  data: [
    {
      type: "column",
      dataPoints: [
        { x: 10, y: 71 },
        { x: 20, y: 55 },
        { x: 30, y: 50 },
        { x: 40, y: 65 },
        { x: 50, y: 95 },
        { x: 60, y: 68 },
        { x: 70, y: 28 },
        { x: 80, y: 34 },
        { x: 90, y: 14 }
      ]
    }                   
  ]
});

chart1.render();

var chart2 = new CanvasJS.Chart("chartContainer2", {
    title: {
    text: "Spline Chart"
  },
  data: [
    {
      type: "spline",
      dataPoints: [
        { x: 10, y: 71 },
        { x: 20, y: 55 },
        { x: 30, y: 50 },
        { x: 40, y: 65 },
        { x: 50, y: 95 },
        { x: 60, y: 68 },
        { x: 70, y: 28 },
        { x: 80, y: 34 },
        { x: 90, y: 14 }
      ]
    }                   
  ]
});

chart2.render();

$("#exportButton").click(function(){
  html2canvas(document.querySelector("#chartsContainer")).then(canvas => {  
    var dataURL = canvas.toDataURL();
    var pdf = new jsPDF();
    pdf.addImage(dataURL, 'JPEG', 20, 20, 170, 120); //addImage(image, format, x-coordinate, y-coordinate, width, height)
    pdf.save("CanvasJS Charts.pdf");
  });
});
</script>
</html>

 

See also  Javascript Tensorflow.js Realtime Webcam Face Landmark Detection Using Blazeface Models Full Project For Beginners

 

 

 

Leave a Reply