How to add section break next page using openxml?

允我心安 提交于 2019-12-05 02:07:18

You need to add the section break to the section properties. You then need to append the section properties to the paragraph properties. Followed by appending the paragraph properties to a paragraph.

        Paragraph paragraph232 = new Paragraph();

        ParagraphProperties paragraphProperties220 = new ParagraphProperties();

        SectionProperties sectionProperties1 = new SectionProperties();
        SectionType sectionType1 = new SectionType(){ Val = SectionMarkValues.NextPage };

        sectionProperties1.Append(sectionType1);

        paragraphProperties220.Append(sectionProperties1);

        paragraph232.Append(paragraphProperties220);

The resulting Open XML is:

  <w:p>
    <w:pPr>
      <w:sectPr>
        <w:type w:val="nextPage" />
      </w:sectPr>
    </w:pPr>
  </w:p>

If you create a Word document that looks the way you want the result to look, then open in it in the Open XML Productivity Tool, you can reflect the code and see what C# code would generate the various Open XML elements you are trying to achieve.

First you need to create a break paragraph

Paragraph PageBreakParagraph = new Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Break() { Type = BreakValues.Page }));

Then you need to append the paragraph

wordprocessingDocument.MainDocumentPart.Document.Body.Append(PageBreakParagraph)

You can also specify where to insert it, if you don't want to append it to the end by using the InsertAfter and InsertBefore methods

wordprocessingDocument.MainDocumentPart.Document.Body.InsertAfter(PageBreakParagraph, ReferenceElement);
wordprocessingDocument.MainDocumentPart.Document.Body.InsertBefore(PageBreakParagraph, ReferenceElement);

Edit:

This adds a page break not a section break.

user5497879

this one will add section break at the end of the page

private static void AddSectionBreakToTheDocument(string fileName)
{
    using (WordprocessingDocument mydoc = WordprocessingDocument.Open(fileName, true))
    {
        MainDocumentPart myMainPart = mydoc.MainDocumentPart;
        Paragraph paragraphSectionBreak = new Paragraph();
        ParagraphProperties paragraphSectionBreakProperties = new ParagraphProperties();
        SectionProperties SectionBreakProperties = new SectionProperties();
        SectionType SectionBreakType = new SectionType() { Val = SectionMarkValues.NextPage };
        SectionBreakProperties.Append(SectionBreakType);
        paragraphSectionBreakProperties.Append(SectionBreakProperties);
        paragraphSectionBreak.Append(paragraphSectionBreakProperties);
        myMainPart.Document.Body.InsertAfter(paragraphSectionBreak, myMainPart.Document.Body.LastChild);
        myMainPart.Document.Save();
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!