ydoow ydoow - 1 year ago 2267
HTML Question

Print page using html2canvas

I'm bring 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);

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

Answer Source

Finally I figure out the solution. The previous handling I used should be made into 2 parts.

1) use html2canvas to render the page into image and store it in a hidden div, when the page is loaded.

html2canvas(divprint, {
    onrendered: function(canvas) {
        var canvasImg = canvas.toDataURL("image/jpg");
        $('#divhidden').html('<img src="'+canvasImg+'" alt="">');

2) Once a print button is clicked, open a new window, write the stored div content and jquery function for printing when the loading is done.

    var printContent = document.getElementById("divhidden");
    var printWindow = window.open("", "","left=50,top=50");                
    printWindow.document.write("<script src=\'http://code.jquery.com/jquery-1.10.1.min.js\'><\/script>");
    printWindow.document.write("<script>$(window).load(function(){ print(); close(); });<\/script>");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download