Introduction
I began my journey down Word Automation and found good articles here. Unfortunately, I hit a big road block: I couldn't choose which printer to print to. I could only print to whichever printer was the ActivePrinter
when the Word object was created. Everywhere I looked I was told that all you had to do was:
WordApp.ActivePrinter = "Printer name"
This didn't work for me, it would just hang. I believe that this is due to different versions, and some might have never had the problem I did, but if you're like me, then read on and you won't have to deal with all the headache I had. Hope it helps.
Background
Word Automation is simply being able to use another application within another. Sounds simple enough, but it can get ugly pretty fast and I have found very few resources for when you hit a problem.
Using the Code
Attached is a VB.NET project that allows you to print a specified Word document. The code is given here.
Make sure to add a reference to the Word Object Library found in the COM tab. (To add a reference, right-click on project and select Add Reference.)
Declare variables on show file and print dialogs to get user input:
Dim f As New OpenFileDialog
Dim p As New PrintDialog
Dim app As Word.Application
Dim doc As Word.Document
If f.ShowDialog = Windows.Forms.DialogResult.OK Then
If p.ShowDialog = Windows.Forms.DialogResult.OK Then
Create a Word application object:
app = New Word.Application
This is where you need to use the WordBasic
property to set the active printer.
app.WordBasic.FilePrintSetup(Printer:=p.PrinterSettings.PrinterName, _
DoNotSetAsSysDefault:=1)
The rest of the code simply opens the document, prints it, and quits the Word application:
Dim filename As Object = f.FileName
Dim m As Object = System.Reflection.Missing.Value
doc = app.Documents.Open(filename, m, m, m, m, m, m, m, m, m, m, m)
app.PrintOut()
app.Documents.Close()
app.Quit()
app = Nothing
End If
End If
The most important line in the above code is this:
app.WordBasic.FilePrintSetup(Printer:=p.PrinterSettings.PrinterName, _
DoNotSetAsSysDefault:=1)
For those who need the above in C#, here it is:
object wb = app.WordBasic;
object[] argValues = new object[] {p.PrinterSettings.PrinterName, 1};
String [] argNames = new String [] {"Printer","DoNotSetAsSysDefault"};
wb.GetType().InvokeMember("FilePrintSetup",BindingFlags.InvokeMethod,null,
wb,argValues,null,null,argNames);
I hope this helps people, because it really got me out of a bind.
History
- 9th June, 2007: Initial post