Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Word document header/footer in php

Tags:

html

php

I have add header/footer are in document in php. but i have footer content twice in last page. I have user this code:-

    <html  xmlns:o='urn:schemas-microsoft-com:office:office'
    xmlns:w='urn:schemas-microsoft-com:office:word'
    xmlns='http://www.w3.org/TR/REC-html40'>
    <head>
        <title>Generate a document Word</title>
        <!--[if gte mso 9]-->
    <xml>
        <w:WordDocument>
            <w:View>Print</w:View>
            <w:Zoom>90</w:Zoom>
            <w:DoNotOptimizeForBrowser/>
        </w:WordDocument>
    </xml>
    <!-- [endif]-->
    <style>
        p.MsoFooter, li.MsoFooter, div.MsoFooter{
            margin: 0cm;
            margin-bottom: 0001pt;
            mso-pagination:widow-orphan;
            font-size: 12.0 pt;
            text-align: right;
        }


        @page Section1{
            size: 29.7cm 21cm;
            margin: 2cm 2cm 2cm 2cm;
            mso-page-orientation: landscape;
            mso-footer:f1;
        }
        div.Section1 { page:Section1;}
    </style>
</head>
<body>
    <div class="Section1">
        <h1>Hello World!</h1>
    <br clear=all style='mso-special-character:line-break;page-break-after:always' />
    <div style='mso-element:footer' id="f1">
        <p class=MsoFooter>
            Page <span style='mso-field-code:" PAGE "'></span>
        </p>
    </div>
</body>
</html>



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

there is an error for the last page. It displays the footer content twice, after the content of the page also.

like image 228
user2729379 Avatar asked Oct 03 '22 02:10

user2729379


1 Answers

You need to insert the HTTP Header at the top of the page. The HTTP Headers should be always declared before anything is printed on the page.

<?php
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=HelloWorld.doc");
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=Windows-1252">
<title>Hello World</title>
<style>
<!--
 /* Style Definitions */
 p.MsoNormal
    {margin:0cm;
    margin-bottom:.0001pt;
    font-size:12.0pt;
    font-family:"Times New Roman";}
-->
</style>
</head>
<body>
<p class=MsoNormal>Hello World</p>
</body>
</html>

Also, you can have a look at the PHPWord library. It'll make your life easier: https://github.com/PHPOffice/PHPWord

like image 167
Wissam El-Kik Avatar answered Oct 05 '22 16:10

Wissam El-Kik