How to implement print functionality efficiently in Javascript?

Javascript provides a very easy way to print your page.

Just use window.print() and the entire page gets printed.

But the problem is exactly that , the entire page gets printed.

If you have a print button , the print button gets printed as well.

If you want only a specific portion of your page to get printed , you can’t do that in a straightforward way.

Here is a recipe to overcome these problems:

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:

Let me create a html page where I want to implement the print functionality:


<html>

<body>

This is my home page .

<button onclick="javascript:window.open('print.html');">Print</button>

</body>


</html>

This page does nothing other than displaying the message “This is my home page” and providing a print button to the user.

When user clicks the print button we are just opening another page in the same path “print.html”.

Here is the home page:

Here is the print.html page:


<html>


<body>

Here is my print content:

Hello World!


</body>


</html>

Here is the print page:

We want to print the above page rather than just open it in a separate window.

To do this , on the onload method of this page call window.print():


<html>


<body onload = "javascript:window.print();">

Here is my print content:

Hello World!


</body>


</html>

Now when you click print button in the home page , print is triggered:

There is one issue here.

When you finish printing , the user is shown print.html page .

But we want to return to the home page.

To enable this use onafterprint() method like below:


<html>


<body onload = "javascript:window.print();" onafterprint="javascript:window.close();">

Here is my print content:

Hello World!


</body>


</html>

Now when you click on print button in the home page , the contents in the print.html page get printed and also the user is redirected to the home page as the print window gets closed.

A seamless experience for the user!

You have absolute control as what to show and how to present them on your printed page using the above recipe!


Posted

in

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading