PHPBuilder - Creating MS Word documents on the fly Page 3



RSS Twitter
Articles Application Architecture

Creating MS Word documents on the fly - Page 3

by: Khairul Amri Yunus
|
December 2, 2003

Improving the code

The above code will return an error if the specified bookmark is not found in the document. To check whether the bookmark exists in the template document, use this:

<?php
if($word->ActiveDocument->Bookmarks->Exists($bookmarkname)) 
{
    
//then create a Range and perform the substitution<br>
    
$objBookmark $word->ActiveDocument->Bookmarks($bookmarkname);
    
$range $objBookmark->Range;
    
//now substitute the bookmark with actual value
    
$range->Text $current_date;

}
?>
The approach above replaces Bookmarks with the actual value, therefore the word highlighted and defined as the bookmark will be deleted. If you want to insert text before the bookmark, use the following:

<?php
$range
->InsertBefore("Today's date is: ");
?>
Alternatively, to insert text after the bookmark, use this:

<?php
$range
->InsertAfter("Have a nice day!");
?>
To select all of the text within the template document, use the following:

<?php
$pagecontent 
$word->ActiveDocument->Content->Text;
?>
To automatically load the document, use header functions (add this to the end of the PHP file):

<?php
header
('Content-Type: application/msword');
header("Content-Disposition: attachment; filename=\"Reminder New.doc\"");
readfile($new_file);
?>
Alternatively, to prompt Open/Save dialog box, use:

<?php
header
('Content-Type: application/msword');
header("Content-Disposition: attachment; filename=\"Reminder New.doc\"");
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
readfile($new_file);
?>
Note that the above two examples may not work on certain browsers and/or versions.
You may want to terminate/kill WINWORD.EXE instance if the code triggers an error or terminates unexpectedly. Run Windows Task Manager and end WINWORD.EXE instance.
That's it. Feel free to share your thoughts and improved versions of the above code.
Khairul Amri Yunus
Kometsoft (M) Sdn. Bhd.

« Previous Page
1
|
2
|
3

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Khairul Amri Yunus

Comment:



Comment:

(Maximum characters: 1200). You have characters left.