Monday 21 July 2014

Tagged under: , , ,

Print Web Page using JavaScript

Many a times, we come across situations where we have to selectively print only a certain part of a web page. When it comes to a normal print command, it will print the entire web page for you. However, what if you want only a certain section, say a certain <div>...</div> to be printed, and exclude the content of the rest of the page?
This tutorial aims at doing just the thing...

Step 1: Enclose the content that you want to be printed in a <div> tag, and name it, say 'report':

<div id="report">
.
.
Your Content goes here...
.
.
</div>

Step 2: Add a print button:

<input type="button" value="Print Summary" onclick="printContent('report')"/>

As we see in the above snippet, 'printContent()' is the function that would do the printing job for us. To this function, we pass the id of the <div> tag whose content we want to print.

Step 3: Create a javaScript function 'printContent()':
At the bottom of the page, add the below javascript function

<script type="text/javascript">
<!--
function printContent(id){
str=document.getElementById(id).innerHTML
newwin=window.open('','printwin','left=100,top=100,width=400,height=400')
newwin.document.write('<HTML>\n<HEAD>\n')
newwin.document.write('<TITLE>Summary</TITLE>\n')
newwin.document.write('<script>\n')
newwin.document.write('function chkstate(){\n')
newwin.document.write('if(document.readyState=="complete"){\n')
newwin.document.write('window.close()\n')
newwin.document.write('}\n')
newwin.document.write('else{\n')
newwin.document.write('setTimeout("chkstate()",2000)\n')
newwin.document.write('}\n')
newwin.document.write('}\n')
newwin.document.write('function print_win(){\n')
newwin.document.write('window.print();\n')
newwin.document.write('chkstate();\n')
newwin.document.write('}\n')
newwin.document.write('<\/script>\n')
newwin.document.write('</HEAD>\n')
newwin.document.write('<BODY onload="print_win()">\n')
newwin.document.write(str)
newwin.document.write('</BODY>\n')
newwin.document.write('</HTML>\n')
newwin.document.close()
}
//-->
</script>

The above function will take the id of the <div> tag whose content we want to print.
And there you are!! You can now print the page. With the help of software like PDF Creator, now you can also selectively print the page to a PDF file.
This functionality can be used where you want to print reports, receipts etc.

Kindly Bookmark and Share it:

2 comments:

  1. Hey keep posting such smart and important articles.

    ReplyDelete
  2. Casino-branded bonus code for November 2021 - JTM Hub
    This week, we'll 전라남도 출장샵 be covering the various 평택 출장마사지 games, the 김천 출장마사지 bonuses, and banking 태백 출장샵 methods for casino players. To find 대구광역 출장샵 out more about bonuses,

    ReplyDelete