DEV Community


A recipe to implement print functionality efficiently in Javascript

vijaysrj profile image Vijay SRJ ・1 min read

Javascript provides the method window.print() to print the entire contents of a html page.

There are two problems with this approach:

  1. You cannot print part of your HTML page
  2. If you have a print button to print the page , even the button shows up in the printed page.

To overcome this problem , here is a recipe to use window.print() efficiently:

STEP1: Create a HTML page with exactly the contents you want to print

STEP2: On onload() method of this html page body , call window.print() , so that when the page is loaded print functionality is triggered

STEP3: Place the print button on the page you want the user to trigger the print button.

STEP4: On click of the print button , open the html page that you created with the print contents (using method)

STEP5: Use the inbuilt onafterprint() method to close the print window once the print is completed (use window.close() method inside it).

Here is a demo :


Editor guide