Thursday 16 April 2015

Print content of div without opening new window

function PrintDiv(contents, callback) {
    var frame1 = document.createElement('iframe');
    frame1.name = "frame1";
    frame1.id = "framePrint";
    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><style type="text/css" 
                                               media="print">@@page  {  size: auto; margin: 5mm 0mm 0mm 10mm;  } 
                                              </style>');
    frameDoc.document.write('</head><body>');
    frameDoc.document.write(contents);
    frameDoc.document.write('</body></html>');
    frameDoc.document.close();
    setTimeout(function () {
        window.frames["frame1"].focus();
        var ua = window.navigator.userAgent;
        var msie = ua.indexOf("MSIE ");

        if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
            var result = $("#framePrint")[0].contentWindow.document.execCommand('print', false, null);
            if (!result) {
                window.frames["frame1"].contentWindow.print()
            }
        }
        else {
            window.frames["frame1"].print();
        }

        document.body.removeChild(frame1);
        if (typeof (callback) == "function") {
            callback();
        }
    }, 500);

}