1

I have the below code

function PrintImage(id) {
    var canvas = document.getElementById(id);
    var win = window.open();
    win.document.write("<br><img src='" + canvas.toDataURL() + "'/>");
    win.print();
    win.location.reload();
}

I am trying to print the chart that i render through Chart JS. It is working in IE but not in chrome. Can someone have a look at the code and tell me what I might be doing wrong. In chrome the print window opens but it is just all white.

Thanks

SP1
  • 1,182
  • 3
  • 22
  • 47

1 Answers1

1

The snippet below runs on JSFiddle. Remember to enable pop ups for chrome, if you want your pop ups not to get blocked by chrome have a look at this question.

function PrintImage() {
    id = 'chart';
    var canvas = document.getElementById(id);
    var win = window.open(canvas.toDataURL(), '_blank');
    
    win.document.write("<br><img src='" + canvas.toDataURL() + "'/>");
    win.print();
    win.location.reload();
}
 

function drawImage(){
    var ctx = $("canvas")[0].getContext("2d"),
        img = new Image();
    
    img.onload = function(){
        ctx.drawImage(img, 0, 0, 500, 500);
        $("span").text("Loaded.");
    };
    img.src = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ7udaoWuG0i57WCc7OyxkWG0jCkqMIBa7D7ff2Dk1Fk7rCsoQr";
    img.crossOrigin ="anonymous";
    $("span").text("Loading...");
}

$("#add").click(drawImage); 
$("#print").click(PrintImage);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
    <head>
        <title>Canvas Replace</title>       
    </head>

    <body>
        <button id="add">Add Image</button><span></span>
        <button id= "print">Print Image</button>
        <canvas width="500" height="500" id='chart'></canvas>
    </body>
    
    
</html>
Jesse Reza Khorasanee
  • 3,140
  • 4
  • 36
  • 53