To place a bookmark, simply open an existing document, place the
cursor in the desired location, and select Insert
Bookmark. In the pop-up window, type in a name for the bookmark and
press the Add button. Create bookmarks on the customer address line
and in the delivery, item, and total fields. The names of those
bookmarks should be customer,
delivery, item, and
total, respectively.
To move to a bookmark directly in PHP, we can use:
$word->Selection->Goto(what, which, count, name);
Using Word's macro language to determine the desired
parameters for this method, we find that
what requires the value
wdGoToBookmark and that
name refers to the name that we gave to
our bookmark. With a little digging through Microsoft documentation,
we also find that count indicates which
instance of the bookmark in the document and that
which is a navigational parameter, of
which our desired value is wdGoToAbsolute.
Rather than do the positioning from PHP, though, we can create a
macro to perform the find directly:
Sub BkmkCustomer( )
Selection.GoTo What:=wdGoToBookmark, Name:="customer"
End Sub
This macro, which we've named
BkmkCustomer, places the cursor at the bookmark
named customer. Using this macro directly avoids
any potential errors introduced in passing multiple parameters from
PHP to Word. The PHP COM method for this is:
$word->Application->Run("BkmkCustomer");
We can repeat this process for each named bookmark in the invoice.
To reduce the number of bookmarks required, we can create a Word
macro for moving to the next cell in a table:
Sub NextCell( )
Selection.MoveRight Unit:=wdCell
End Sub
Now we can complete the invoice with data we get from an HTML form.
We also want to print the form, though.
If we only wanted to save an electronic copy, it would be as simple
as:
$word->ActiveDocument->SaveAs("c:/path/to/invoices/myinvoice.doc");
This has the side effect of setting the
ActiveDocument->Saved flag to
True, which lets us close the application without
being prompted to save the modified invoice.
If we want to print the document, there are three steps: print, mark
the document as saved so we can quit without a dialog box, then wait
until the printing has finished. Failure to wait means the user will
see a "Closing this application will cancel
printing" warning. Here's the code
for doing this:
$word->Application->Run("invoiceprint");
$word->Application->ActiveDocument->Saved=True;
while($word->Application->BackgroundPrintingStatus>0){sleep (1);}
In this code, we've created a macro,
InvoicePrint, with our desired printer settings.
Once we call the macro, we loop until the value of
BackgroundPrintingStatus is set to 0.