How to Print Contents from Certain DIV

     Time to time we get into such situation when we need to print part of our webpage where pop-up is restricted. Well JavaScript will be the answer. Here is a little script that raise the DIV dynamically and print. It is very effective cross browser script. Feel free implementing it as a starter..

<script language = "javascript" type="text/javascript">
        function printSpecificDiv(divId) {
            var printContent = document.getElementById(divId);
            var windowUrl = 'about:blank';
            var windowName = 'Print' + new Date().getTime();
            var printWindow = window.open(windowUrl, windowName, 'left = 10000, top = 10000, width = 0, height = 0');
            printWindow.document.write(printContent.innerHTML);
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            printWindow.close();
       }
</script>

Another example_
<script language = "javascript" type = "text/javascript">
        function printSpecificDiv(divID) {
            var divElements = document.getElementById(divID).innerHTML;
            var wholePage = document.body.innerHTML;
            document.body.innerHTML = "<html><head><title></title></head><body>" + divElements + "</body>";
            window.print();
            document.body.innerHTML = wholePage;
            return false;
        }
    </script>

=>
<div id = "printThisDiv">
       This part of the page will only be printed!!!
</div>
<input type = "button" value = "Print" onclick = "JavaScript:printSpecificDiv('printThisDiv');" />

No comments:

Post a Comment