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?
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();
});
}
});
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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With