Open In App

How to print a web page using JavaScript ?

Last Updated : 14 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Javascript is the world most popular lightweight, cross-platform, interpreted compiled programming language, along with a scripting language for web. It facilitates the dynamic functionality that helps to make the interactive website. As all the Morden browsers use the Javascript & is a client-side scripting language that helps webserver to read the source code & transmit it over the internet to the client’s computer & run directly on browsers, which, in turn, helps to analyze the behavior of the webpage. It is also used for validations and functionality for user events. Javascript facilitates the ability to print the current web page, which can be saved in the portable document format. In this article, we will discuss how to print the web page in Javascript, along with understanding its implementation through the example. 

The print() method prints the content of the current webpage that may includes the text, images, graphics, etc. If the document is still loading while this function is called when the document ends up the loading process before the print dialog is opened. This method gets blocked while opening the print dialog.

Syntax: 

window.print();

Parameter: This method does not take any parameter.

Return value: It does not return any value.

Approach: Create a button with an onClick event that is attached with the printpage() method, & it should be triggered when we want to print the page. When the user clicks the button then printpage() method (in the script tag) will be called, which may contains some code that helps to print the page. After this, a dialog box will appear that will contains the option to save the document.

Example: This example describe the use of the print() method to print the current webpage in Javascript.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <title>Javascript print() Method</title>
</head>
  
<body>
    <h2>GeeksforGeeks</h2>
  
    <h4>Javascript print() Method</h4>
  
    <p>
        A Computer Science portal for geeks.
        It contains well written, well thought
        and well explained computer science and
        programming articles.
    </p>
  
    <button onclick="printpage()" style="color:white;
                   background-color: red; 
                   font-weight: bold;">Click to Print
    </button>
      
    <script>
        function printpage() {
            window.print();
        }
    </script>
</body>
  
</html>


Output:

Javascript print() Method



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads