Move Cursor to End of Word Document, Insert Section Break, Insert DOCX into another DOCX File using C# .NET

I’m using this code to insert a DOCX at the end of another DOCX:
string strSummary = @"…\Docs\Summary\MergeTest.docx";
string strInsert = @"…\Docs\Agreements\Incubation Kit A.docx";
Aspose.Words.Document mainDoc = new Aspose.Words.Document(strSummary);
Aspose.Words.Document subDoc = new Aspose.Words.Document(strInsert);

        Aspose.Words.Paragraph para = new Aspose.Words.Paragraph(mainDoc);
        Aspose.Words.Run run = new Aspose.Words.Run(mainDoc);
        para.Runs.Add(run);
        mainDoc.LastSection.Body.AppendChild(para);
        InsertDocument(para, subDoc);
        mainDoc.Save(strSummary);

This finishes without error but the sub doc is not inserted at the but but it has overwritten somehow the first document. It looks like the sub doc is on a layer on top of the first document. Any ideas how I can only add the sub doc at the end of the first doc?

@tpalmie,

Please try the following simple code:

Document docMain = new Document("C:\\temp\\input.docx");
DocumentBuilder documentBuilder = new DocumentBuilder(docMain);
documentBuilder.MoveToDocumentEnd();
documentBuilder.InsertBreak(BreakType.SectionBreakNewPage);

Document docSub = new Document("C:\\temp\\second.docx");
documentBuilder.InsertDocument(docSub, ImportFormatMode.KeepSourceFormatting);

docMain.Save("C:\\temp\\20.10.docx");

In case the problem still remains, then please ZIP and attach the following resources here for testing:

  • Your simplified main Word document
  • Your simplified sub Word document
  • Aspose.Words for .NET 20.10 generated output DOCX file showing the undesired behavior
  • Your expected DOCX file showing the desired output. You can create this document manually by using MS Word.
  • Please also create a standalone simple Console application (source code without compilation errors) that helps us to reproduce your current problem on our end and attach it here for testing. Please do not include Aspose.Words DLL files in it to reduce the file size.

As soon as you get these pieces of information ready, we will start investigation into your particular scenario/issue and provide you more information.