Friday, June 7, 2013

Print a particular div of a webpage

While working in a web page, we were required to print only one section (say a div content) of a page. There is a single line Javascript code to do printing.
 
"window.print();"
However, this function would print the whole page content, which is not what we want.

Solution:
To meet the above objective we try out some alternatives like -
 
        1) Put media css "display:none" for other element except the div to print.
             i.e
                <style type="text/css" media="print" >
           .nonPrintable{display:none;} /*class for the element we don’t want to print*/
          </style>
 
        2) Dynamically create a document and open in a new window. The popup window will only contain the content of the div which is to be printed.
 
On body load of the opened child window we will simply call window.print() method. Now the current window contains only the parent div contens,so our problem is solved.
I implemented the second technique and it works great with all the browsers. So I am sharing the code below. Copy paste the following code and save it with .html extension. Run in browser (allow block content for IE)

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
     <script type="text/javascript">     
        function PrintDiv() {    
           var divToPrint = document.getElementById('divToPrint');
           var popupWin = window.open('''_blank','width=300,height=300');
           popupWin.document.open();
           popupWin.document.write('<html><body onload="window.print()">' + divToPrint.innerHTML + '</html>');
            popupWin.document.close();
                }
     </script>
   </head>
        <body >
                other contents
            <div id="divToPrint" >
               <div style="width:200px;height:300px;background-color:teal;">
                  This is the div to print
                </div>
            </div>
            <div>
                <input type="button" value="print"onclick="PrintDiv();" />
            </div>
        </body> 
</html>