Search code examples
c#openxmlopenxml-sdkwordprocessingmlpower-tools-for-xml

Replace Section Break with Page Break


I am trying to merge some word documents into a single word document using DocumentBuilder from OpenXml Powertools. This is the code used for merge:

var sources = new List<Source>();
                foreach (var doc in documents)
                {
                    var wmlDoc = new WmlDocument(doc.Path);

                    sources.Add(new Source(wmlDoc, doc.PageBreak));
                }

                var newDestinationDocument = DocumentBuilder.BuildDocument(sources);

Each object from documents contains a path to the document and a bool which says if I want or not a Page Break inserted after the document.

This code is working but the problem is that I get a Section Break instead of a Page Break, I know that the second parameter from the Source constructor represents a Section Break bool, but I need a Page Break instead.

This is what the resulted document contains after meging: enter image description here

And I need something like this:

enter image description here

I can not use altChunks, Interop or any paid library for this.


Solution

  • You have to add

    <w:br w:type="page" />
    

    for the beginning or ending of the document paragraph for the document you want to separate with page breaks.

    Before you apply your code try the following -

    WordprocessingDocument myDoc = WordprocessingDocument.Open(@"file path", true);
    MainDocumentPart mainPart = myDoc.MainDocumentPart;
    OpenXmlElement last = myDoc.MainDocumentPart.Document
        .Body
        .Elements()
        .LastOrDefault(e => e is Paragraph || e is AltChunk);
    last.InsertAfterSelf(new Paragraph(
        new Run(
            new Break() { Type = BreakValues.Page })));
    mainPart.Document.Save();
    

    I have chosen the last paragraph of the file. You can chose to do the same for the first of the document as well based on your requirement.

    The above code will add the <w:br w:type="page" /> which adds a manual page break.

    You can also try using <w:pageBreakBefore/> to the last paragraph of the documents which specifies to the client(MS Word etc.) that the paragraphs that follow this tag will be rendered on a new page.