Make your own free website on Tripod.com

How to print via scripting

In Netscape Navigator 4 and Internet Explorer 5 this is supported by the window method print( ). For Internet Explorer 4 we have to include the web browser object in the page, and send it a print command.

Printing via script is not possible in Netscape or Internet Explorer 3.

One feature that I have taken advantage of is that a subroutine can be accessed via the window obect window.functionname. This means we can name the printing subroutine print and if we call window.print( ) on the click of the print button, Netscape will call its built in print method, and Internet explorer will call our print routine. This little routine is written in VBScript so Netscape will ignore it. The catch will be: when Internet explorer starts to support the print method we will have to modify our code. We would probably have to change the code then any way to account for a new web browser object.

The final consideration is, what happens when the user cancels the print or there is some printing error, or their browser doesn't support printing? All we need to do is trap the errors, and check if there was one after issuing the print command.

Try it now! -->>     
Here is the code for a simple print page:
<html>
<head>
<script language="javascript">
<!--
// a little variable because IE3 isn't nice about testing
// for objects in vbscript
DA = (document.all) ? 1 : 0
window.onerror=handle_error
function handle_error()
{
	msg="\nNothing was printed. \n\nIf you do want to print this page,"
	msg+="then\nclick on the printer icon in the toolbar above."
	alert(msg)
	// to cancel the script error warning
	return true;
}
//-->
</script>
<SCRIPT LANGUAGE="VBScript">
sub print
	olecmd = 6    ' Print Command
	oleparam = 1
	on error resume next
	WB.ExecWB olecmd, oleparam
	if err.number <> 0 then
	   if DA then ' ie4 - user probably cancelled
		alert "Nothing was printed."
	   else  ' ie3 - give other instructions
		handle_error
	   end if
	end if
end sub
</SCRIPT>
</head>
<body>
<form>
	<Input type=button value="print page" onclick="window.print();">
</form>
<OBJECT ID="WB"
  WIDTH=0 HEIGHT=0
  CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2">
</OBJECT>
</BODY>
</HTML>


Check out the printing article on the Microsoft MSDN Workshop site that shows some alternatives, including a solution for printing frames.
My Tripod homepage  :   Comments and corrections welcome to housten@hotmail.com or my guestbook.