StanSight.Com E-Mail: Stan@StanSight.Com StanSight.Com Banner
Tutorials: JavaScript - Print Page Function

I wrote this small JavaScript Print function to allow you to place a button anywhere on a page so a user can send the page to a printer. This is great for when you do not want the user to have search around for a print icon on their web browser, or for when you have opened a window that does not display the icons at the top, but you still want to give the user the ability to print.

Click on the button below to see how it works:
This JavaScript print function is compatible with NetScape Navigator and Microsofts Internet Explorer, versions 4, 5, and above.

The Script
If it were not for supporting multiple types of browsers this would be trivial. As it is there is a special VBscript routine that has to be used for Windows users of IE4. The script is well documented, so you sould be able to follow what it is doing. If not, then don't worry. Simply copy and paste the following code anywhere between the <head> and </head> tags of your web page.

<script language="JavaScript" type="text/JavaScript"> <!-- function PrintPage() { // Get browser version and operating system information var agt=navigator.userAgent.toLowerCase() IE = (agt.indexOf("msie") != -1); Ver = parseInt(navigator.appVersion); Win = ( (agt.indexOf("win")!=-1) || (agt.indexOf("16bit")!=-1) ); IE4Win = (IE && (Ver = 4) && Win); // If the print method is available then use it (supported by NetScape and IE5) if (window.print) { window.print(); // Else if this is an IE4 browser AND // running on windows then call the IE4 VBScript print function } else if (IE4Win) { IE4PrintPage(); } // Else it is an older browser, so only send a message to the screen else if (Win) { alert("I'm sorry, but you will need to click your browser's Print button to print this page"); } } // --> </script> <script language="VBScript" type="text/VBScript"> <!-- sub IE4PrintPage() ' ' Use VBScript to execute the browsers print routines in IE4 (windows version) ' OLECMDID_PRINT = 6 OLECMDEXECOPT_DONTPROMPTUSER = 2 OLECMDEXECOPT_PROMPTUSER = 1 on error resume next call browser.ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_PROMPTUSER) end sub --> </script>
The Button
To create a button that when pressed, calls the javascript print function, simply place the following HTML anywhere in the body of your page.
<form> <input type="button" value='Click to Print' onClick="PrintPage();" /> </form>