I'm struggling to print the contents of a div tag without a pop up window
My code looks like this at the moment
var DocumentContainer = document.getElementById('print');
var WindowObject = window.open('', 'Completed Registration Form', 'width=750,height=650,top=50,left=50,toolbars=no,scrollbars=yes,status=no,resizable=yes');
WindowObject.document.writeln(DocumentContainer.innerHTML);
WindowObject.document.close();
WindowObject.focus();
WindowObject.print();
WindowObject.close();
The below uses a popup window, is there a way to not do this using a popup window.
There is a more efficient way - without jQuery or any other library
The idea is to replace the window with a hidden iframe, and print the contents of the iframe.
here is the code for that:
function ClickHereToPrint(){
try{
var oIframe = document.getElementById('ifrmPrint');
var oContent = document.getElementById('divToPrint').innerHTML;
var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
if (oDoc.document) oDoc = oDoc.document;
oDoc.write('<head><title>title</title>');
oDoc.write('</head><body onload="this.focus(); this.print();">');
oDoc.write(oContent + '</body>');
oDoc.close();
} catch(e){
self.print();
}
}
This considers that you have an iframe in your page. if you don't, just create one using: document.createElement('iframe')
Try this function-
function PrintDiv(divid,title) {
var contents = document.getElementById(divid).innerHTML;
var frame1 = document.createElement('iframe');
frame1.name = "frame1";
frame1.style.position = "absolute";
frame1.style.top = "-1000000px";
document.body.appendChild(frame1);
var frameDoc = frame1.contentWindow ? frame1.contentWindow : frame1.contentDocument.document ? frame1.contentDocument.document : frame1.contentDocument;
frameDoc.document.open();
frameDoc.document.write(`<html><head><title>${title}</title>`);
frameDoc.document.write('</head><body>');
frameDoc.document.write(contents);
frameDoc.document.write('</body></html>');
frameDoc.document.close();
setTimeout(function () {
window.frames["frame1"].focus();
window.frames["frame1"].print();
document.body.removeChild(frame1);
}, 500);
return false;
}
https://jsfiddle.net/rtg37u94/
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