February 25, 2014

Automate Word document print using Delphi

Automating Microsoft office Word from Delphi is really easy. I already blogged on the subject. This time, I will show you how to select a specific printer in your Delphi application and instruct Word to use that printer.

Using Delphi, create a new VCL forms application and drop a TComboBox, a TButton and a TWordApplication. Add the unit Printers to the uses clause. In the FormShow event handler, we will fill the combobox with the available printers:
procedure TForm1.FormShow(Sender: TObject);
    ComboBox1.Items     := Printer.Printers;
    ComboBox1.ItemIndex := Printer.PrinterIndex;
In the button's OnClick event handler, add the following code:
procedure TForm1.Button1Click(Sender: TObject);
    ADoc : _Document;
    WordApplication1.Visible := TRUE;
    ADoc := WordApplication1.Documents.Add(emptyParam,
                                        emptyParam, emptyParam, emptyParam);
    WordApplication1.Selection.Text := 'Embarcadero Delphi Rocks !' + #13 +
                                       'http://www.overbyte.be' + #13#10;
    WordApplication1.ActivePrinter := ComboBox1.Text;

This code connect the application to Microsoft Word, launching Word if required. It makes Word visible on screen (by default it is not shown). It then insert some nice text in the document. To select the printer Word must use, it is enough to assign the property ActivePrinter with the name of the printer. We pick the name from the combobox. Finally, the document is printed out and the application disconnect from Word. That's it!

Follow me on Twitter
Follow me on LinkedIn
Follow me on Google+
Visit my website: http://www.overbyte.be

1 comment:

Unknown said...

AHWord97.pas is a superb example of how to use word automation.

Even though it was written a long time ago it compiles with relatively little effort and works with every version of word i've tested it on.