Search code examples
javascriptjqueryhtmlhtml2canvas

How to use html2canvas to print web page?


I want to have my page print exactly like it's shown on screen, and found a script called html2canvas: http://html2canvas.hertzen.com/documentation.html

See my implementation below.

I have 2 problems:

  1. When I click the print button, Chrome shows the print dialog, but the page is shown 2 times - first the regular print version, and after that html2canvas render. Obviously I don't need the regular print... I tried to hide 'body', but that didn't help.

(Edit: fixed this one: 2. I don't want divs with "#hidden-print" show up on the render. But even when I hide it like shown in my code, it still shows up. Anyone knows how to make sure this is not shown in the render? )

    $('#print').on('click', function(){

        html2canvas(document.body, {
            onrendered: function(canvas) {
                $('#hidden-print').hide();
                document.body.appendChild(canvas);
                window.print();
                $('canvas').remove();
                $('#hidden-print').show();
            }
        });
    });

Solution

  • Between appending the canvas and printing, add a style rule to hide all descendents of body except the canvas, not the body element itself. Obviously don't forget to remove it afterwards.

    var hide = $('<style>').html('body *:not(canvas) { display: none !important; }').appendTo(document.head);
    ... // print
    hide.remove();