Print Webpage Using JavaScript
Last Updated : Jul 1, 2023
IN - JavaScript | Written & Updated By - Pragati
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.
CHECK OUT THIS TUTORIAL LIVE DEMO →
To Print Webpage It Takes Only One Step:-
- 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.
I hope this tutorial on print webpage using JavaScript helps you and the steps and method mentioned above are easy to follow and implement.