Posted By

fackz on 12/20/13


Tagged

div print area


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

fackz


Print only the contents of a div


 / Published in: JavaScript
 

URL: http://www.huntingground.freeserve.co.uk/main/mainfram.htm?../scripts/printing.htm

Although there is not a simple command that allows the printing of part of a document there are a couple of methods that can be used. You can use CSS by creating a seperate style sheet to hide any content that is not required for printing or you can use a script. The basic idea is that because the print command prints the whole page you create a new page containing only the text you want to print and print that page.

  1. <script type="text/javascript">
  2. <!--
  3. function printContent(id){
  4. str=document.getElementById(id).innerHTML
  5. newwin=window.open('','printwin','left=100,top=100,width=400,height=400')
  6. newwin.document.write('<HTML>\n<HEAD>\n')
  7. newwin.document.write('<TITLE>Print Page</TITLE>\n')
  8. newwin.document.write('<script>\n')
  9. newwin.document.write('function chkstate(){\n')
  10. newwin.document.write('if(document.readyState=="complete"){\n')
  11. newwin.document.write('window.close()\n')
  12. newwin.document.write('}\n')
  13. newwin.document.write('else{\n')
  14. newwin.document.write('setTimeout("chkstate()",2000)\n')
  15. newwin.document.write('}\n')
  16. newwin.document.write('}\n')
  17. newwin.document.write('function print_win(){\n')
  18. newwin.document.write('window.print();\n')
  19. newwin.document.write('chkstate();\n')
  20. newwin.document.write('}\n')
  21. newwin.document.write('<\/script>\n')
  22. newwin.document.write('</HEAD>\n')
  23. newwin.document.write('<BODY onload="print_win()">\n')
  24. newwin.document.write(str)
  25. newwin.document.write('</BODY>\n')
  26. newwin.document.write('</HTML>\n')
  27. newwin.document.close()
  28. }
  29. //-->
  30. </script>
  31.  
  32. Usage:
  33.  
  34. <DIV id="print_div1">Your content</div>
  35. <a href="#null" onclick="printContent('print_div1')">Click to print div 1</a>
  36.  
  37. On clicking the link the following sequence of events happens.
  38.  
  39. A new window is opened
  40. The contents of the div are dynamically written to the new window
  41. Data is sent to the printer
  42. The new window is automatically closed (IE only)

Report this snippet  

You need to login to post a comment.