unable to add background color to the canvas using jspdf and chartjs
16,794
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:
Author by
user3501278
Updated on June 22, 2022Comments
-
user3501278 almost 2 years
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
-
heman123 over 6 yearsthis is just a work around ! isn't there any other way to add background to the pdf image provided by library ?