Hi,

I want to add Some text and images into word file as
Header and footer.

How to create word file through php code.

I have uploaded Sample doc file.

Plz guide me..

Dani AI

Generated

was right that HTML-based tricks can sometimes produce headers/footers, but that approach is brittle for automated generation. A more reliable solution is to create native .docx files from PHP. The PHPOffice PHPWord library supports headers, footers, images and page numbering and works without Microsoft Word installed.

Example (composer install phpoffice/phpword):

require 'vendor/autoload.php';

$phpWord = new \PhpOffice\PhpWord\PhpWord();

$section = $phpWord->addSection();

$header = $section->addHeader();
$header->addImage(DIR . '/logo.png', ['width' => 100, 'height' => 40, 'alignment' => 'center']);
$header->addText('Company Name', ['size' => 12], ['alignment' => 'center']);

$footer = $section->addFooter();
$footer->addPreserveText('Page {PAGE} of {NUMPAGES}.', [], ['alignment' => 'center']);
$footer->addText('Confidential', ['size' => 10], ['alignment' => 'center']);

$writer = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$writer->save('output.docx');

Practical tips and caveats: PHPWord produces .docx (not the legacy .doc binary). If a .doc is mandatory and you are on Windows, PHP COM automation is an option but is not recommended for unattended server use (see PHP manual on COM). Ensure image paths are absolute and readable by the PHP process, watch memory limits for large images, and when streaming to the browser set the correct Content-Type and use php://output. For complex, repeatable layouts, create a Word template and use PHPWord's TemplateProcessor to replace placeholders.

References: PHPWord project and docs are a good starting point (PHPWord GitHub, PHPWord docs). For COM automation details see the PHP manual (COM extension).

Recommended Answers

All 2 Replies

Creating a Word file isn't difficult but I don't think that you will be able to create a header and footer. To create the file try this:

I take it back. You can create html that will generate a header and footer in Word but it takes quite a bit of html code. If you want to see what is needed, create a small Word file that includes a header and footer then do a Save As as a web page. If you open the generated html page in Word, you will see that it still has the header and footer. If you look at the html you will see what it takes.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.