aviv
aviv

Reputation: 2809

Word OLE Automation - delete first page and manipulate header and footer

I am using PHP to start Word Automation and manipulate word documents, but i guess it can be done in all any other language. What i need to do is quite simple, i need to remove the first page and add header and footer.

Here is my code:

 $word = new COM('word.applicantion');
 $word->Documents->Open('xxx.docx');
 $word->Documents[1]->SaveAs($result_file_name, 12);

Any samples?

Upvotes: 3

Views: 2662

Answers (2)

aviv
aviv

Reputation: 2809

try { $word = new COM("word.application") //$word = new COM("C:\x.docx"); or die("couldnt create an instance of word");

        //bring word to the front
        $word->Visible = 1;

        //open a word document
        $word->Documents->Open("file.docx");

        // remove first page
        $range = $word->ActiveDocument->Bookmarks("\page");
        $range->Select();
        $word->Selection->Delete();

        //save the document as docx
        $word->Documents[1]->SaveAs("modified_file.docx", 12); // SaveAs('filename', format) // format: 0 - same?, 1 - doc?, 2 - text,  4 - text other encoding
    }
    catch(Exception $e)
    {
        echo "error class.document.php - convert_to_docx: $e 20100816.01714";
    }

    //close word
    if($word)
        $word->Quit();

    //free object resources
    //$word->Release();
    $word = null;

Upvotes: 1

Todd Main
Todd Main

Reputation: 29153

This is the way you could do it in VBA. This can likely be ported to PHP fairly simply.

Sub RemoveFirstPageAndAddHeaderFooter()
    Dim d As Document
    Set d = ActiveDocument
    Dim pageOne As Range
    Set pageOne = d.Bookmarks("\page").Range
    pageOne.Select
    Selection.Delete
    d.Sections(1).Headers(1).Range.Text = "Some text"
    d.Sections(1).Footers(1).Range.InlineShapes.AddPicture "C:\beigeplum.jpg", False, True
End Sub

Note on the ...InlineShapes.AddPicture - the onus would be on you to ensure the picture is the right size. If you want more control over this, you would use .Footers(1).Shapes.AddPicture instead as that let's you set the width/height, top/left, etc.

Upvotes: 2

Related Questions