Word OLE Automation - delete the first page and control the header and footer

I use PHP to run Word Automation and manipulate text documents, but I think it can be done in any other language. What I need to do is pretty simple, I need to delete the first page and add a 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?

+3
source share
2 answers

So you can do it in VBA. This can probably be ported to PHP quite 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

...InlineShapes.AddPicture - , . , .Footers(1).Shapes.AddPicture, /, / ..

+2

      {           $ word = new COM ( "word.application" )//$word = new COM ( "C:\x.docx" );                ( " " );

        //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;
+1

Source: https://habr.com/ru/post/1755988/


All Articles