Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unable to add background color to the canvas using jspdf and chartjs

I am exporting a bar chart to pdf by using jspdf plugin. The bars on the chart is in white color so when I export to pdf ( as a png image) , the bars are not visible on the transparent background in the pdf. I added a gray background color on the container so that the white bars are clearly visible. When I export the graph to pdf, it still shows the transparent background not the gray color. Can someone tell me what i am missing?

javascript:

    $(document).ready(function(){

    $('#hyppdf').click(function(){
    var canvasImg = document.getElementById("myChart").toDataURL("image/png",     
    1.0);
    var doc = new jsPDF();
    doc.setFontSize(33);
    doc.setFillColor(135, 124,45,0);
    doc.addImage(canvasImg, 'png', 10, 10, 150, 100);
    doc.save('sample.pdf');
    })

    var ctx = document.getElementById("myChart").getContext('2d');

  var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["M", "T", "W", "T", "F", "S", "S"],
    datasets: [{
      label: 'apples',
      data: [12, 19, 3, 17, 28, 24, 7],
      backgroundColor: "rgba(255,255,255,1)"
    }, {
      label: 'oranges',
      data: [30, 29, 5, 5, 20, 3, 10],
      backgroundColor: "rgba(255,153,0,1)"
    }]
  }
});

})

html:

    <div class="container" style="background-color:#ccc">
  <h2> <a id="hyppdf" href="#">download</a></h2>
  <div>
    <canvas id="myChart"></canvas>
  </div>
</div>

https://jsfiddle.net/2gnajnz4/5/

Thanks

like image 271
user3501278 Avatar asked Oct 18 '25 07:10

user3501278


1 Answers

I think you can solve your issue by adding a rect to the image before exporting it to pdf:

  doc.setFillColor(204, 204,204,0);
  doc.rect(10, 10, 150, 160, "F");

see updated fiddle:

like image 64
deweyredman Avatar answered Oct 19 '25 21:10

deweyredman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!