Reading and Printing Word Documents in WSH - Printing Word Documents
(Page 2 of 5 )
I also get a lot of readers asking how they can print Word documents from within a WSH script. Many of them are looking for ways to automate report printing or simply to perform batch printing of multiple documents. Whatever your specific need might be, this is a fairly simple task to perform.
Const wdDoNotSaveChanges = 0
strDocument = "C:mydoc.docx"
Set objWord = CreateObject("Word.Application")
objWord.Visible = False
objWord.DisplayAlerts = False
objWord.Documents.Open strDocument,, True
Set objDoc = objWord.ActiveDocument
Once again, you’ll begin by connecting to the Word automation object and opening the document that you wish to print. Here again, I’m keeping the Word application hidden since most automation scripts are designed to run unattended.
objWord.Options.PrintBackground = False
Next, we’re going to turn off Word’s Background Printing feature. An error message is sometimes displayed if the Word object is released before the print job completes. Turning off Background Printing will eliminate this error.
objDoc.PrintOut
Finally, we get to the meat and potatoes of the script. We use the Document object's PrintOut method to send our document to the printer. Note that this method will print to the printer that is found in Word’s default printer setting. In most cases, this will be the last printer that was used within Word. If you would like to print to another printer, or just prevent some unwanted mishaps by specifying a printer, you can use the code below instead.
strActivePrinter = objWord.ActivePrinter
objWord.ActivePrinter = "HP LaserJet 4 local on LPT1:"
objDoc.PrintOut
objWord.ActivePrinter = strActivePrinter
This piece of code first polls the ActivePrinter property for its current value and assigns it to a variable. Then it sets that value manually before calling the PrintOut method. Finally, the ActivePrinter property is set back to its original value.
This does present one major caveat in some cases. Setting the value of the ActivePrinter property in Word will also set the system default printer. You may not wish to change the system’s default printer setting. In the next example, I’ll show you how to set a Word printer setting without changing the system default printer.
objWord.WordBasic.FilePrintSetup "HP LaserJet 4 local on LPT1:", 1
Here I’m using the FilePrintSetup method. This method allows me to specify an optional parameter that tells Word not to set the system default printer when changing its active printer.
objWord.Quit wdDoNotSaveChanges
Now we can close the document and exit the Word application.
If you’re performing batch print jobs, you may want to think of ways to that this functionality could be packaged in a reusable function.
Next: Advanced Printing Options >>
More Windows Scripting Articles
More By Nilpo