Print Multiple Charts in a Page using HTML2Canvas | CanvasJS JavaScript Charts

Print Multiple Charts in a Page using HTML2Canvas | CanvasJS JavaScript Charts

by 규연 황

HTML

<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
<button id="exportButton" type="button">Print Charts</button>
<div id="chartsContainer">
  <div id="chartContainer1" style="height: 300px; width: 100%;"></div>
  <div id="chartContainer2" style="height: 300px; width: 100%;"></div>
  <div class="print">fdsfsdf</div>
</div>

CSS

.print {
  background: red;
  font-size: 30px;
  filter: drop-shadow(10px 10px 10px blue)
}
@media print {
  filter: drop-shadow(10px 10px 10px blue);
  outline: 3px solid pink;
}

JavaScript

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 width = canvas.width;
    var printWindow = window.open("");
    $(printWindow.document.body)
      .html("<img id='Image' src=" + dataURL + " style='" + width + "'></img>")
      .ready(function() {
      printWindow.focus();
      printWindow.print();
    });
  });
});