score:1

Accepted answer

this function prints the contents of a canvas correctly

function printimage() {
    var canvas = document.getelementbyid("bidstatus");
    var win = window.open();
    win.document.write("<br><img src='" + canvas.todataurl() + "'/>");
    win.print();
    win.location.reload();

}

score:3

i was able to use jspdf to print a canvas from chart.js with chrome using the code below. there is already an accepted answer to this question, but as someone else pointed out in the comments, i could not get that solution to work with chrome.

here is a link to jspdf documentation. i am still exploring this so you may find more useful tools to accomplish the same task. i had to use a png instead of a jpeg because of the transparent background of the chart. the jpeg would only appear black. if you want a colored background, add a colored rectangle(rect method in docs) that is the same size and position of the chart image before adding the image. other text and features can also be added to the pdf you are building.

i do not like that the chart image has to be added at a specific location and size and will update this post if i find a better way of doing this.

edit: with jspdf you can use pdf.save('filename.pdf') to replace filesaver.js, provided you want a pdf.

html

<button id="print-chart-btn">print chart</button>
<div class="canvas-container">
    <canvas id="random-chart" ></canvas>
</div>

<script src="https://cdn.jsdelivr.net/npm/jspdf@1.5.3/dist/jspdf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0/dist/chart.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>

javascript

$('#print-chart-btn').on('click', function() {
    var canvas = document.queryselector("#random-chart");
    var canvas_img = canvas.todataurl("image/png",1.0); //jpeg will not match background color
    var pdf = new jspdf('landscape','in', 'letter'); //orientation, units, page size
    pdf.addimage(canvas_img, 'png', .5, 1.75, 10, 5); //image, type, padding left, padding top, width, height
    pdf.autoprint(); //print window automatically opened with pdf
    var blob = pdf.output("bloburl");
    window.open(blob);
});

Related Query

More Query from same tag