Recommended:

  • phpclasses.org
  • jsclasses.org
  • jsmag.com
  • siteapps.com
  • View our reviews on Hot Scripts
  • JS Tutorial
  • scripts.com
  • securesignup.com




Recent Comments

Powered by Disqus




Back to articles

Generate WORD document using PHP

There are two ways of generating word document using PHP. First would be using COM object. Other would be by sending headers and outputting HTML code for browser to interpret as word document.

So for using COM object, here is an example of how to do it:

<?php
// Create new COM object – word.application
$word = new COM("word.application");

// Hide MS Word application window
$word->Visible = 0;

//Create new document
$word->Documents->Add();

// Define page margins 
$word->Selection->PageSetup->LeftMargin = '2';
$word->Selection->PageSetup->RightMargin = '2';

// Define font settings
$word->Selection->Font->Name = 'Arial';
$word->Selection->Font->Size = 10;

// Add text
$word->Selection->TypeText("TEXT!");

// Save document in temp folder
$filename = tempnam(sys_get_temp_dir(), "word");
$word->Documents[1]->SaveAs($filename);

// Close and quit
$word->quit();
unset($word);

header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=document_name.doc");

// Send file to browser
readfile($filename);
//delete temo file
unlink($filename);

?>

And for second option, if you don't know how to output something, like page break, then just create word document with a page break and save it as filtered webpage and look at it's source code. You can find all you need about formatting word as HTML.

And here is a snippet of how it should be done:

<?php

header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=1.doc");
        
?>

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252">
<title>Asdasdasd</title>
<style>
<!--
 /* Style Definitions */
 p.MsoNormal, li.MsoNormal, div.MsoNormal
    {margin:0cm;
    margin-bottom:.0001pt;
    font-size:12.0pt;
    font-family:"Times New Roman";}
@page Section1
    {size:595.3pt 841.9pt;
    margin:2.0cm 42.5pt 2.0cm 3.0cm;}
div.Section1
    {page:Section1;}
-->
</style>

</head>

<body lang=EN>

<div class=Section1>

<p class=MsoNormal><span lang=LV>SOME text</span></p>

<span lang=LV style='font-size:12.0pt;font-family:"Times New Roman"'><br
clear=all style='page-break-before:always'>
</span>

<p class=MsoNormal><span lang=LV>Some text</span></p>

<span lang=LV style='font-size:12.0pt;font-family:"Times New Roman"'><br
clear=all style='page-break-before:always'>
</span>

<p class=MsoNormal><span lang=LV>sometext</span></p>

</div>

</body>

</html>

You may also be interested in:

Powered by BlogAlike.com

blog comments powered by Disqus