Monday, June 5, 2017

Javascript print div

I was searching for a way to print only one div in a webpage using jquery and/or javascript and come across this post which works very well:

https://stackoverflow.com/questions/33732739/print-a-div-content-using-jquery

The only downside is print function opens a new window:
function printDiv() 
{

  var divToPrint=document.getElementById('DivIdToPrint');

  var newWin=window.open('','Print-Window');

  newWin.document.open();

  newWin.document.write('<html><body onload="window.print()">'+divToPrint.innerHTML+'</body></html>');

  newWin.document.close();

  setTimeout(function(){newWin.close();},10);

}
As an alternative, I managed to code a slightly different print function like so:

function printMyDiv(id) {
        var container = document.getElementById(id),
            origDisplay = [],
            origParent = container.parentNode,
            body = document.body,
            childNodes = body.childNodes,
            resetParams,
            handleMaxWidth;

        // hide all body content
        Array.prototype.forEach.call(childNodes, function (node, i) {
            if (node.nodeType === 1) {
                origDisplay[i] = node.style.display;
                node.style.display = 'none';
            }
        });

        // only show our div
        body.appendChild(container);

        // print
        window.focus();
        window.print();
        setTimeout(function () {
            origParent.appendChild(container);
            Array.prototype.forEach.call(childNodes, function (node, i) {
                if (node.nodeType === 1) {
                    node.style.display = origDisplay[i];
                }
            });
        }, 1000);

    }

No comments:

c# httpclient The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch

 If we get this error while trying to get http reponse using HttpClient object, it could mean that certificate validation fails for the remo...