How to add a button to print an HTML page?


To add a “PRINT” button on your HTML webpage which, when clicked, prints the whole webpage. This is a fairly simple functionality to add in a webpage and can be added using some HTML elements and plain JavaScript.

Therefore, let us discuss the approach for doing so.

Approach

  • Firstly, add a <input /> tag inside the HTML dom.

  • Assign its type attribute to “button” and give it some value.

  • Then assign an “onclick” handler to the input which will be handled using JavaScript.

  • The function that handles the click event of input tag will look like this −

const handlePrint = () => {
   window.print();
}

The complete code for this approach will be −

Example

<!DOCTYPE html>
<html lang="en-US">
<head>
   <title>
  	   Adding Print Button
   </title>
</head>
   <body style="color: black;">
      <h1>Hello World!</h1>
      <p>Welcome to my Website</p>
      <p>
         This website is built using plain JS and HTML.
      </p>
      <p>
      Okay Bye!!!
      </p>
      <input value='Print' type='button' onclick='handlePrint()' />
      <script type="text/javascript">
         const handlePrint = () => {
            var actContents = document.body.innerHTML;
            document.body.innerHTML = actContents;
            window.print();
         }
      </script>
   </body>
</html>

Updated on: 09-Feb-2023

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements