12

I want to add a section break at the end of the document and add some text.

My code is as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace WordDocManipulation
{
    class Program
    {
        static void Main(string[] args)
        {

            string path = @"C:\sample.docx";
            string strtxt = "Hello This is done by programmatically";      

           OpenAndAddTextToWordDocument(path,strtxt);
        }
        public static void OpenAndAddTextToWordDocument(string filepath, string txt)
        {
            /* I want to the below text to be added in the new section */ 

            // Open a WordprocessingDocument for editing using the filepath.
            WordprocessingDocument wordprocessingDocument =
                WordprocessingDocument.Open(filepath, true);

            // Assign a reference to the existing document body.
            Body body = wordprocessingDocument.MainDocumentPart.Document.Body;

            // Add new text.
            Paragraph para = body.AppendChild(new Paragraph());
            Run run = para.AppendChild(new Run());
            run.AppendChild(new Text(txt));

            // Close the handle explicitly.
            wordprocessingDocument.Close();
        }
    }
}

What should I do?

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Mohemmad K
  • 809
  • 7
  • 33
  • 74

3 Answers3

15

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.

embedded.kyle
  • 10,976
  • 5
  • 37
  • 56
  • 1
    While this DOES indeed insert a section break, there's a problem when it comes to the final document page properties. The entire document (before inserting a section break) likely has a specific `sectionProperties` entry at the end. When adding a break the pages before loose those properties. Any idea how to make sure the page properties aren't lost? – MBender May 25 '16 at 10:46
  • 1
    @Shaamaan If you're creating an entirely new document in OpenXML, then there will be no problem. You create a `new SectionProperties()` and `Append` your properties to it. Nothing will be overwritten. If you're trying to modify an existing document, then you will need to retrieve the exiting `SectionProperties` and either loop through them, changing what you need, or appending anything new that you like. You'd start with `var sections = docPart.Document.Descendants();` [Example available here](https://msdn.microsoft.com/en-us/library/office/gg308472(v=office.14).aspx). – embedded.kyle May 26 '16 at 17:41
5

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.

Mohamed Sherief
  • 209
  • 2
  • 8
0

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();
    }
}
Alejandro
  • 7,290
  • 4
  • 34
  • 59
  • I tried this and it seems it works fine, what if i want insert a Section Break to the first page (cover page) and at the end of the document, so in other words i have two section breaks to insert, in first page, and at the end of the document, your method did the second (at the end of the document) – AIMEN BOULAHIA Jan 25 '21 at 08:34