Why are the use of page printing in JS?

Asked 19-Jul-2021
Viewed 386 times

2 Answers


0

Many times you would like to place a button on your webpage to print the content of that web page via an actual printer. JavaScript helps you to implement this functionality using the print function of the window object.

The JavaScript print function window.print() prints the current web page when executed. You can call this function directly using the onclick event as shown in the following example.

<html>
   <head>      
      <script type = 'text/javascript'>
         <!--
         //-->
      </script>
   </head>
   
   <body>      
      <form>
         <input type = 'button' value = 'Print' onclick = 'window.print()' />
      </form>   
   </body>
<html>

 


1

Page print in JavaScript is a simple code in JavaScript used to print the content of the web pages.
• The print() method prints the contents of the current window.
• It basically opens Print dialog box which lets you choose between various printing options.
Syntax

 window.print();
Exapmle

 <!DOCTYPE html>
<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta charset='utf-8' />
    <title>Print page</title>
    <style>
        body {
            background-color:red;
            text-align:center;
        }
    </style>
</head>
<body>
    <button name='btn' id='btn' onclick='window.print()' >Print this page</button>
</body>
</html>