Monday, November 06, 2006

How to generate Microsoft Word Documents using PHP and COM?

COM is available only in Windows (for example if you are running Apache on Windows XP). By using COM you can launch Microsoft Word or any other available component (or custom component made by you and registered with regsvr32), fill in a document template and save the result as a Word document (as .doc, .rtf or other available formats) and send it to the users of your website.
It's very easy to use it. The code below shows how to create a Word .doc file:
<?php
$word = new COM("word.application");
//To see the version of Microsoft Word, just use $word->Version
echo "I'm using MS Word {$word->Version}<br>";
//It's better to keep Word invisible
$word->Visible = 0;
//Creating new document
$word->Documents->Add();
//Setting 2 inches margin on the both sides
$word->Selection->PageSetup->LeftMargin = '2"';
$word->Selection->PageSetup->RightMargin = '2"';
//Setup the font
$word->Selection->Font->Name = 'Verdana';
$word->Selection->Font->Size = 8;
//Write some text
$word->Selection->TypeText("Hello, universe!");
//Save the document as DOC file
$word->Documents[1]->SaveAs("D:\hello.doc");
// or use: $word->Documents[1]->SaveAs("C:htdocshello2.rtf",6); to save as RTF file
// or use: $word->Documents[1]->SaveAs("C:htdocshello2.htm",8); to save as HTML file
//And of course, quit Word
$word->quit();
//$word->Release();
$word = null;
//Give the user a download link
echo '<a href="hello2.doc">Download file as .doc</a>';
?>

No comments: