Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a canvas element?

I have a canvas element on my page. I draw an image over it and some data that the user entered. On a press of a button I want to send the canvas to printer, to print it on paper. I tried to use this plug-in: jQuery.printElement, like that:

the button code:

<a href="javascript:print_voucher()">PRINT</a>

'print_voucher()' function:

function print_voucher()
{
    $("#canvas_voucher").printElement();
}

canvas_voucher is the ID of my canvas element. It printed the page, but didn't print the canvas. I tried to use it like that as well:

$("#canvas_voucher img").printElement();

But that didn't even start the printer.

So how can I do that? How can I print the content of the canvas?

**EDIT** Here's the code that creates my canvas and tries to create an image with it:

function create_voucher(visitor_name, visitor_identity_num, unique_number)
{
var canvas = $("#canvas_voucher")[0];
if (canvas.getContext)
{
    var ctx = canvas.getContext('2d');

    // Draw image
    var img = new Image();
    img.src = 'https://someurl.com/image.jpg';

    img.onload = function(){
        ctx.drawImage(img,0,0);
        ctx.fillStyle="#CCC";
        ctx.font="bold 20px Arial";
        ctx.fillText(visitor_name, 750, 270);
        ctx.fillText(visitor_identity_num, 750, 295);

        ctx.font="bold 25px Arial";
        ctx.fillText(unique_number, 620, 325);
    }
    var voucher = canvas.toDataURL("image/png");
    $("#voucher_img").attr("src", voucher);
} else {
    alert('You need Safari or Firefox 1.5+ to see this.');
}

}

like image 487
Igal Avatar asked Dec 09 '22 15:12

Igal


1 Answers

This will convert the canvas to a .png image URL and open it in a new browser window

The Print Dialog is triggered to let the user print the page.

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

Here is example code:

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){

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

    ctx.fillStyle="gold";
    ctx.strokeStyle="blue";
    ctx.lineWidth=5;
    ctx.rect(50,50,100,100);
    ctx.fill();
    ctx.stroke();

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

    $("#printVoucher").click(function(){ print_voucher(); });


}); // end $(function(){});
</script>

</head>

<body>
    <canvas id="canvas" width=300 height=300></canvas><br>
    <button id="printVoucher">Print</button>
</body>
</html>
like image 191
markE Avatar answered Jan 02 '23 16:01

markE