#native_company# #native_desc#

Creating MS Word documents on the fly

By Khairul Amri Yunus
on December 2, 2003


Printing HTML pages directly from browsers usually does not give the best printing
output, compared to output from word processors such as Microsoft Word. For
web-based systems that generate letters, reports and documents, an output that
looks authentic and original is very important. Furthermore, printing output
directly from browsers is usually dependant on the browser’s configuration. Therefore
web-based applications may face difficulties in giving the best printing output
especially when dealing with large user base.
This article provides a guideline on how to generate documents and letters in
MS Word format using a pre-defined template. My customer (a government agency)
required for Reminder Letters to be generated automatically in MS Word format
from the Loan Management System that I delivered to them. Using this approach,
they can generate a Reminder Letter for each loan which then can be printed
nicely and saved for future reference.
This solution can be accomplished using COM extension. Please note that the
server running this code MUST have MS Word installed.


Lets start with the big picture. This is how it works:
  1. First, we need to prepare a MS Word document (*.doc) that contains the sample
    output. The content of the Reminder Letter is normally the
    same, except for, in each case we need to put the Applicant Name, Loan Reference
    Number and Today’s date in the letter to be generated.
  2. In this MS Word template document, we need to define places where PHP should
    insert the actual value (such as one pulled from database or evaluated from code).
    This can be done using the “Bookmark” feature in MS Word documents.
  3. Our PHP code will substitute the Bookmark with the actual value.
  4. And finally, we save it as a new document.
Preparing the MS Word Template
This step is actually simple, all we need is a MS Word document (*.doc) that
contains the sample output and Bookmarks.
To create a Bookmark in a MS Word document, click on Insert/Bookmark. You can
highlight a word or sentence and make them a Bookmark. In this code, we will
substitute the Bookmark with the actual value, therefore the word you highlighted
and saved as a Bookmark will be substituted.
A Bookmark name can only contain letters, numbers and underscores. To see all of
bookmarks in the document, click on Tools/Options and check Bookmarks under Show
group in the View tab.
The code we use in the next section just substitutes a specified bookmark with text,
therefore the formatting, images, tables and etc will not be lost.