Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print page using html2canvas

I'm building a print page function on my web using html2canvas.

function printthispage() {

    html2canvas($("#mydiv"), {
        onrendered: function (canvas) {
            var myImage = canvas.toDataURL("image/png");
            var printWindow = window.open(myImage);                        
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            printWindow.close();
        }
    });
}

However the window opened and closed immediately. I've tried removing close(), the image showed on new window but no print function was triggered. Is there something wrong?

like image 216
ydoow Avatar asked Jun 24 '26 09:06

ydoow


2 Answers

Try this,it will work:

html2canvas($("#mydiv"), {
    onrendered: function(canvas) {
        var myImage = canvas.toDataURL("image/png");
        var tWindow = window.open("");
        $(tWindow.document.body)
            .html("<img id='Image' src=" + myImage + " style='width:100%;'></img>")
            .ready(function() {
                tWindow.focus();
                tWindow.print();
            });
    }
});
like image 82
soundhiraraj Avatar answered Jun 26 '26 22:06

soundhiraraj


Vanilla JS solution

// render HTML to canvas based on target element
html2canvas(document.querySelector('<YOUR SELECTOR>'), {

  // if the canvas is rendered
  onrendered: function (canvas) {

    // create a new window
    var nWindow = window.open('');

    // append the canvas to the body
    nWindow.document.body.appendChild(canvas);

    // focus on the window
    nWindow.focus();

    // print the window
    nWindow.print();

    // reload the page
    location.reload();
  }
});
like image 22
0x1ad2 Avatar answered Jun 26 '26 21:06

0x1ad2



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!