Search code examples
c#ms-wordoffice-interoplandscape

c# interop Word insert landscape page


I´m trying to insert a landscape page into a Word document. But it changes all the pages to landscape. How can I insert only one landscape page in my word document?

My code:

object wdSectionBreakNextPage = 2;
        //object pageBreak = 7; //el 7 es el tipo. https://learn.microsoft.com/en-us/dotnet/api/microsoft.office.interop.word.wdbreaktype?view=word-pia
        rngDoc.Select();
        //rngDoc.InsertBreak(pageBreak);
        rngDoc.InsertBreak(wdSectionBreakNextPage);
        rngDoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
        rngDoc.PageSetup.DifferentFirstPageHeaderFooter = 0;
        Microsoft.Office.Interop.Word.Paragraph para = rngDoc.Paragraphs.Add();
        para.Range.InsertParagraphAfter();

Solution

  • Inserting a section break is a good first step - that's required.

    The problem is coming from this line, which I assume is directing Word to apply the page orientation to the entire document. (You don't actually specify what is assigned to rngDoc, but the behavior you describe indicates it's the entire document.)

    rngDoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
    

    If it should be applied only to the new section then that section needs to be specified. Again, we have no idea what rngDoc.Select() is actually doing, since we have no context. In any case, performing a selection is irrelevant and the line is not needed. Something along these lines:

    object objWdSectionBreakNextPage = 2; //Don't confuse with the actual enum name!
    //get the index number of the section where rngDoc is located
    int nrSections = rngDoc.Sections[1].Index; 
    rngDoc.InsertBreak(objWdSectionBreakNextPage);
    //set rngDoc to the new section
    rngDoc = Doc.Sections[nrSections + 1].Range;
    rngDoc.PageSetup.Orientation = WdOrientation.wdOrientLandscape;
    rngDoc.PageSetup.DifferentFirstPageHeaderFooter = 0;
    Microsoft.Office.Interop.Word.Paragraph para = rngDoc.Paragraphs.Add();
    para.Range.InsertParagraphAfter();