Click to return to the Server Technologies home page    
Web Workshop  |  Server Technologies

Using ASP and WSH to Print on Your Intranet


Jeff Sandquist
Microsoft Corporation

March 30, 1999

The following article was originally published in the MSDN Online Voices "Servin' It Up" column.

Welcome to the new and improved "Servin' It Up". As we mentioned last month, the column will now focus on Active Server Pages (ASP) technology. I'll be taking the reins from Tom Moran, who has moved over to the Web Men Talking column in MSDN Online Voices. I hope to lead you through some really cool ASP solutions. So on with the show!

The Scenario

You are developing a Web-based application for your local intranet, and you want complete control over the output that your user prints from your Web application (don't we all?). You could just allow the user to click the print button on their Web browser. You ask, "Isn't there a way I can do this from the server?" The answer is yes: print from ASP.

The Application

We'll create a recursive ASP page that will pass information from a form to the Microsoft® Windows® Scripting Host (WSH) and output the results to a printer on your local network. Recursion, which is used to have a page call itself from within itself, is an important programming technique for ASP.

Caveats

You will need ASP, Microsoft Windows Scripting Host, and a Microsoft Visual Basic® Scripting Edition (VBScript) version that supports the FileSystemObject object. Microsoft Windows NT 4.0 Option Pack Non-MSDN Online link installs all of these technologies. For the latest version of the Scripting Engines or to install WSH, visit the Microsoft Scripting Technologies Web site Non-MSDN Online link.

Let's Get on with the Application

Create an ASP file called ASPPrint.asp. When developing your pages, establish a standard for naming your variables and stick to it. I personally prefer to use Hungarian Notation. In fact, I suggest you tell twelve of your friends to use Hungarian notation also. One of our readers didn't use Hungarian notation and fell off a cliff. Another of our readers used Hungarian notation and won a million dollars!

First, we will define the values used in our page and retrieve the value of our submit button from the forms collection. Note how we use the Option Explicit statement to force explicit declaration of all variables our script.

<%@ Language=VBScript %>
<%
Option Explicit

Dim strSubmit         'Form value for the Submit Button
Dim strPrinterPath    'Form value for Network Path to Printer
Dim strUsername       'Form value for Username
Dim strPassword       'Form value for Password
Dim strMessage        'Form value for Message to Print
Dim objFS             'VBScript File System Object
Dim objWSHNet         'Windows Scripting Host Network Object
Dim objPrinter        'Printer Object to stream text to

strSubmit = Request.Form("Submit")
%>

<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
</HEAD>
<BODY>

Since this will be a recursive, or reentrant, ASP page, it first checks the value of the Submit button to decide what action needs to be performed.

<%
'
' If we have not received the results from the form we must
' display it.
'
If strSubmit = "" Then
%>

If the value of the form is empty, the HTML form is displayed. We will use this form to retrieve the network path to the printer, the user name, password, and finally, the message that we would like to print.

<FORM action="ASPPrint.asp" method=POST id=form name=form>
   <TABLE WIDTH=100% ALIGN=center BORDER=0 CELLSPACING=1 CELLPADDING=1>
      <TR>
         <TD ALIGN=right NOWRAP>Network Path to the Printer:</TD>
         <TD ALIGN=left NOWRAP><INPUT type="text" id=printerpath name=printerpath 
            value="\\< Domain >\< Printer >"></TD>
      </TR>
      <TR>
         <TD ALIGN=right NOWRAP>Login ID:</TD>
         <TD ALIGN=left NOWRAP><INPUT type="text" id=username name=username 
            value="<% = strUsername %>"></TD>
      </TR>
      <TR>
         <TD ALIGN=right NOWRAP>Password:</TD>
         <TD ALIGN=left NOWRAP><INPUT type="password" id=password 
            name=password></TD>
      </TR>
      <TR>
         <TD ALIGN=right NOWRAP>Message to print:</TD>
         <TD ALIGN=left NOWRAP><TEXTAREA rows=2 cols=20 id=message 
            name=message></TEXTAREA></TD>
      </TR>
      <TR>
         <TD ALIGN=right NOWRAP>&nbsp;</TD>
         <TD ALIGN=left NOWRAP><INPUT type="submit" value="Submit" 
            id=submit name=submit></TD>
      </TR>
   </TABLE>
</FORM>

Note   This is not secure; I've shown it merely for illustration purposes. For security reasons, you would not want to send your Windows NT user account information over the network in plain text. Ideally, you would create an account and assign it print permissions to the network printer. You could then hard code this information in your ASP page. If you really need to send the account information over the network safely, you will need to use a Secure Sockets Layer (SSL) connection.

When our form is submitted, the following code retrieves the values from our form.

<%
Else
   '
   ' Get information from our form
   '
   strPrinterPath = Request.Form("printerpath")
   strUsername = Request.Form("username")
   strPassword = Request.Form("password")
   strMessage = Request.Form("message")

We will now use the VBScript FileSystemObject object and the WSH Network object. The Network object will give us the methods we need to open a printer connection, and the FileSystemObject will allow us to stream our output to the printer. We create these objects in the following code example:

   '
   ' Create FileSystem Object and Windows Scripting Host Network Object
   '
   Set objFS = CreateObject("Scripting.FileSystemObject")
   Set objWSHNet = CreateObject("WScript.Network")

The AddPrinterConnection method maps the remote printer specified by strPrinterPath to the local resource name. In this example, we use LPT1. We populate this connection with the values previously retrieved from our form collection.

   ' Connect to Network Printer from Windows Scripting Host
   '
   objWSHNet.AddPrinterConnection "LPT1", strPrinterPath, False, strUsername, strPassword

With the connection established, we use FileSystemObject to stream the message to the printer.

   '
   ' Open Print device as a file using the File System Object
   '
   Set objPrinter = objFS.CreateTextFile("LPT1:", True)
   '
   ' Send text to print device using the File System Object
   '
   objPrinter.Write(strMessage)

Error trapping is always a good idea. The following section will trap for errors while closing the connection to our printer object. For production code, supply this type of error handling throughout your page.

   '
   ' Close the print device object and trap for errors
   '
   On Error Resume Next
   objPrinter.Close
   '
   ' If an error has occurred while closing the printer connection,
   ' output what went wrong.
   '
   If Err Then
      Response.Write ("Error # " & CStr(Err.Number) & " " & Err.Description)
      Err.Clear    
   Else

If we've made it to the following section, the operation has been successful. We send a friendly confirmation message to the browser.

      '
      ' The operation succeeded.  Output a confirmation
      '
      Response.Write("<CENTER>")
      Response.Write("<TABLE WIDTH=100% ALIGN=center BORDER=0 CELLSPACING=1 CELLPADDING=1>")
      Response.Write("<TR><TD ALIGN=RIGHT><B>Message Sent:</B></TD>")
      Response.Write("<TD ALIGN=LEFT>" & strMessage & "</TD></TR>")
      Response.Write("<TR><TD ALIGN=RIGHT><B>Path to Network Printer:</B></TD>")
      Response.Write("<TD ALIGN=LEFT>" & strPrinterPath & "</TD></TR>")
      Response.Write("<TR><TD ALIGN=RIGHT><B>Login ID:</B></TD>")
      Response.Write("<TD ALIGN=LEFT>" & strUsername & "</TD></TR>")
      Response.Write("</TABLE>")
      Response.Write("</CENTER>")
   End If

Finally, we remove the printer connection and clean up our objects.

   '
   ' Remove the printer connection 
   '
   objWSHNet.RemovePrinterConnection "LPT1:"
   Set objWSHNet  = Nothing
   Set objFS      = Nothing
   Set objPrinter = Nothing
End If
%>
</BODY>
</HTML>

The power of ASP is that it is an automation interface. Through this interface, you can access Windows Scripting Host and ultimately, through its properties and methods, connect to your network printers.

Jeff Sandquist is one of Microsoft's finest Canucks, and is a member of the Active Server Pages Escalation Team at Microsoft Developer Support.



Back to topBack to top

Did you find this material useful? Gripes? Compliments? Suggestions for other articles? Write us!

© 1999 Microsoft Corporation. All rights reserved. Terms of use.