Free Support Forum - aspose.com

Programmatically Merge Two or Multiple Word Documents into One File using C# .NET | Keep Formatting | Headers Footers

We use Aspose.Word to merge 2 word documents into one. One document contains header and footer and second has only a body. In most cases everything works good but we found one document which cause a problem.
Here is a test app:
WordTest.zip (101.7 KB)

Steps to reproduce:

  1. Open project in Visual Studio and send Aspose license
  2. Run the app, select a destination folder and press a button.
  3. In the destination folder you will find merge.docx file. Open it. First page of this document is a blank page (with header and footer) so the body starts from page 2 (and should from page 1).

FYI: When we merge the same files using Word application, then body starts from page 1.

If you need more info, please let me know.

Thanks

@ManMasterDevelopment,

You can simply remove the only empty Paragraph from “hf.docx”:

public static void MergeHeaderFooterWithBody(Document hfDocument, Document body)
{
    Paragraph removeMe = hfDocument.LastSection.Body.LastParagraph;

    Node insertAfterNode = hfDocument.FirstSection.Body.FirstChild;
    CompositeNode dstStory = insertAfterNode.ParentNode;

    // This object will be translating styles and lists during the import.
    NodeImporter importer = new NodeImporter(body, hfDocument, ImportFormatMode.KeepDifferentStyles);

    // Loop through all sections in the source document.
    foreach (Section srcSection in body.Sections)
    {
        // Loop through all block level nodes (paragraphs and tables) in the body of the section.
        foreach (Node srcNode in srcSection.Body)
        {
            // Let's skip the node if it is a last empty paragraph in a section.
            if (srcNode.NodeType.Equals(NodeType.Paragraph))
            {
                Paragraph para = (Paragraph)srcNode;
                if (para.IsEndOfSection && !para.HasChildNodes)
                    continue;
            }

            // This creates a clone of the node, suitable for insertion into the destination document.
            Node newNode = importer.ImportNode(srcNode, true);

            // Insert new node after the reference node.
            dstStory.InsertAfter(newNode, insertAfterNode);
            insertAfterNode = newNode;
        }
    }

    removeMe.Remove();
}

The code seems to start inserting nodes from “body.docx” after the only empty Paragraph of “hf.docx”. However, MS Word pushes that empty Paragraph to the end of merged file (you can observe two empty Paragraphs at the end of MS Word’s generated DOCX).

Thanks for this solution. I will use it. So for now this issue is solved.

@ManMasterDevelopment,

In case you have further inquiries or may need any help in future, please let us know by posting a new thread in Aspose.Words forum.