Do you want to be a good Web Developer?

Enter Your Email To Get Our Exclusive Tutorials
And Offer Right In Your Email

Join TalkersCode Community And Recieve Exclusive Tutorials
On Web Development Right Via Email.

Print Webpage Using JavaScript

Thursday, Jan 12, 2017

Tags:- JavaScript


In this tutorial we will show you how to print webpage or print a particular area in a webpage using JavaScript.There are many plugins for webpage printing but in this tutorial we will print webpage without any plugin.You may also like take webpage screenshot using JavaScript.


See Demo
Print Webpage Using JavaScript


To Print Webpage It Takes Only One Step:-

  1. Make a HTML file and define markup and scripting


Step 1.Make a HTML file and define markup and scripting

We make a HTML file and save it with a name print.html

<html>
<head>
<script type="text/javascript">
function print_webpage()
{
 var printContent = document.getElementsByTagName('body')[0];
 var WinPrint = window.open('', '', 'width=700,height=650');
 WinPrint.document.write(printContent.innerHTML);
 WinPrint.document.close();
 WinPrint.focus();
 WinPrint.print();
 WinPrint.close();
}

function print_div()
{
 var printContent = document.getElementById('print_div');
 var WinPrint = window.open('', '', 'width=700,height=650');
 WinPrint.document.write(printContent.innerHTML);
 WinPrint.document.close();
 WinPrint.focus();
 WinPrint.print();
 WinPrint.close();
}
</script>
</head>
<body>
<div id="wrapper">
<h1>Print Webpage Using JavaScript</h1>
<input type="button" class="print_button" value="Print Webpage" onclick="print_webpage();">
<input type="button" class="print_button" value="Print Div Only" onclick="print_div();">
<div id="print_div">
<p>
Some sample content and this is a demo to print webpage using javascript 
Some sample content and this is a demo to print webpage using javascript
Some sample content and this is a demo to print webpage using javascript
Some sample content and this is a demo to print webpage using javascript
Some sample content and this is a demo to print webpage using javascript
Some sample content and this is a demo to print webpage using javascript
</p>
</div>
</div>
</body>
</html>

In this step we create a sample div and insert some sample content for printing and we create two buttons one is used to print complete webpage and another is used to print 'print_div'.We created two functions to print webpage and 'print_div' both the functions uses same method to print the content.You may also like add spell checker in your webpage using jQuery.



Thats all, this is how to print webpage using JavaScript.You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

Join Us With Our 21000+ Subscribers And Get Our Latest Tutorials Update Via Email