Print from javascript
You can’t actually print a document from javascript, but you can open the print dialog to the user.
Did you know that it’s possible to popup the print dialog window to your users?
You can not in any way force the user to print with any normal programming, but you can always help your user by opening the print dialog.
I will give you three different ways, to help you handle all cases you might find.
Example 1:
The first is to open the print dialog with a form-button or a link.
| <form> <input type=”button” value=”Print This Page” onClick=”window.print()” /> </form> |
Example 2:
This one first pops up a popup, and then from the initiating window askin the popup to print it self. This can be useful if you don’t have access over the text in the popups. Pretty basic the same thing as the first example, but instead of calling “print()” on window, we call it on thePopup which has the referecnce to our popup.
| <script language=”JavaScript”> var thePopup = window.open(‘myPopupFile.php’,'myPopupFile’,'width = 250, height = 250′); </script> <form> |
Example 3:
This one is a really special one… I got the code from a friend, and have changed it a little to make more use for me. Sometimes you want to print more than one document without needing to ask the user to click lots of links. This one is one solution to handle the problem/issue.
Basicly we load all the pages we want to print in a frameset, and then call a function called a function via “onLoad()” that prints all the frames. The onLoad() function is automaticly called when all the frames are loaded, which should be when they are ready to be printed.
Look in the printAllViaFrames() function now, since there are some special things. First we go through the number of frames available, so you never need to change the function to handle more frames. The next thing is the magic… We don’t want all documents to start print at the same time, so we use “setTimeout” to schedule the function print() on the different frames.
The first fram is printed after one second (1000 miliseconds), the next 6 seconds (1000+5000 milis), the next after 11 seconds. That should make the print pages pretty dislplayed for the user .
| <script language=”JavaScript”> function printAllViaFrames() { for (var i=0; i < frames.length; i++) { setTimeout(‘frames[' + i + '].print()’, 1000 + 5000 * i); } } </script> <frameset onLoad=”printAllViaFrames()” rows=”*,*,*”> |
Good luck with your printing
And remember, there are no way with html-programming to force the print function to print on a printer without user interaction.

January 28th, 2010 at 1:16 am
hey, thanks for the quick and easy tip.
February 8th, 2010 at 3:07 pm
You are most welcome! Hope you enjoy the tutorials!
February 25th, 2010 at 5:52 pm
Thanks for sharing.. was realy helpful.