DEV Community

Vijay SRJ
Vijay SRJ

Posted on

1 1

A recipe to implement print functionality efficiently in Javascript

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 window.open() 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 :

https://fullstackdeveloper.guru/2020/12/02/how-to-implement-print-functionality-efficiently-in-javascript/

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay