Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing the contents of a div tag without a POP-Up window in Javascript

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.

like image 1000
Elitmiar Avatar asked Dec 01 '22 08:12

Elitmiar


2 Answers

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')

like image 128
Stefan Avatar answered Dec 05 '22 17:12

Stefan


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;
}

Fiddle Link

https://jsfiddle.net/rtg37u94/

like image 21
Ashok Kumawat Avatar answered Dec 05 '22 17:12

Ashok Kumawat