none
Classic ASP web page calling Powershell to print a Word document

    Question

  • Question: Can I automate Word, to only print an HTML file by calling Powershell from the server side (IIS)?

    We are moving many classic ASP pages from an old 2003 server to a 2012 server - no problem with that part, but to couch what we're doing I added it.

    Several of those apps accept user input into form data and then the report is sent via email and/or sent to a printer.  I can that just fine.  While testing the printouts I was asked if the font could be larger by the folks using the report.  So, I found where I could use Word as a conduit to print the report and enlarge the font.

    When I run the Powershell script in the Windows Powershell ISE - SUCCESS!  Mostly anyway - in order to use the correct printer I need to change the default printer in Powershell - not ideal.

    When I fill in the form and call the Powershell script server side (IIS) it will not print - I get this error ($Error object):

    -2146233087 - You cannot call a method on a null-valued expression.^Line: $output = $pdoc.PrintOut()

    Here's how I'm using Powershell:

    <#
        .SYNOPSIS
            Test script for printing to a specific printer, which must be installed on the server.
    #>

    Function LogWrite
    {
       Param ([string]$logstring)

       Add-content $Logfile -value $logstring
    }

    $FileName = $args[0]
    $PrinterName = $args[1]
    $Logfile = $args[2]     #"c:\temp\CLINICAL_SVCS_script.log"
    $strReturn = "0^Successful"

    #Send To named printer
    try
    {
    #Print a file from Microsoft Word (which can apply formatting changes)
    $WordObj=New-Object -ComObject Word.Application
    $Doc = $WordObj.Documents.Open($FileName)
    $WordObj.Visible = $true
    $pdoc = $WordObj.activeDocument

    #Change the Default Printer
    (Get-WmiObject -ComputerName . -Class Win32_Printer -Filter "Name='$PrinterName'").SetDefaultPrinter()

    #Send To Default Printer
    $output = $pdoc.PrintOut()
    $output | Out-Printer #-name $PrinterName  -InputObject $output

    #Close File without saving 
    $Doc.Close([ref]0)
    $WordObj.quit()

    }
    catch
    {
        $strMessage = $error[0].Exception.Message
        $strHResult = $error[0].Exception.HResult
        $strLine = $error[0].InvocationInfo.Line
        $strReturn = "1^Error attempting to print report.^" + $strHResult + "^" + $strMessage + "^Line: " + $strLine
    }
    finally
    {
        # garbage collection
        [gc]::collect() 
        [gc]::WaitForPendingFinalizers()
    }

    # write to a log file
    #  Log file time stamp:
    $LogTime = Get-Date -Format "MM/dd/yyyy@hh:mm:ss"
    $LogRecord = $LogTime + "^" + $FileName + "^" + $PrinterName + "^" + $strReturn
    LogWrite $LogRecord

    $strReturn

    Friday, September 4, 2015 3:18 PM

Answers