JavaScript

How to Print a Page in JavaScript?

JavaScript has the ability to integrate the HTML elements to provide a wide range of features. Printing a web page is an important feature of JavaScript. JavaScript serves a lot of methods to serve various purposes. Similarly, to print a webpage, the window.print() method is used to print the webpage using JavaScript.

This post provides a deep insight on how to print a page in JavaScript.

How to Print a Page in JavaScript?

In JavaScript, the window.print() method is utilized for printing the current web-page. The window object is utilized to call the print() method in JavaScript. The print() method is employed to provide the printing functionality. It sends the complete content of the web page to the user’s printer. The syntax of the window.print() method is provided below:

Syntax

window.print()

The window.print() method neither accepts parameters nor returns anything.

Example

Another example is followed by a user-defined method for printing a page in JavaScript. By considering the user defined method, the code is as follows.

Code

<html>

<body>

<h2>Example using user defined method in JavaScript </h2>

<button onclick="user_defined_method()">Please Press Button</button>

<p> Welcome to JavaScript</p>

<script>

   function user_defined_method()

    {

  window.print();

    }

 </script>

</body>

</html>

The description of the code is as follows:

  • An HTML button is created which will call the user_define_method() on its oclick event.
  • Inside the <script> tag, the function user_defined_method() is created which contains the window.print() method inside it.

Output

It is observed from the output, that if a user presses button “Please Press Button” the print dialgoue is opened which will enable you to print the web-page.

Conclusion

The window.print() method is used to print a page in JavaScript. Whenever the window.print() method is applied the print dialgoue box will appear which will enable you to print the web-page. This post provides a detailed guide to print a page in JavaScript. To achieve this, we have provided a detailed explanation of the window.print() method with the help of suitable examples.

About the author

Syed Minhal Abbas

I hold a master's degree in computer science and work as an academic researcher. I am eager to read about new technologies and share them with the rest of the world.