How do I insert section with document builder?

Document blockDocument = new Document(args.Replacement);
DocumentBuilder templateDocumentBuilder = new DocumentBuilder(_baseDocument);

templateDocumentBuilder.MoveTo(args.MatchNode);
NodeImporter importer =
    new NodeImporter(blockDocument, _baseDocument, ImportFormatMode.KeepSourceFormatting);
foreach (Aspose.Words.Section srcSection in blockDocument.Sections.OfType<Aspose.Words.Section>())
{
    AsposeSection s = importer.ImportNode(srcSection, true) as AsposeSection;

    templateDocumentBuilder.CurrentSection.PageSetup.Orientation = srcSection.PageSetup.Orientation;
    templateDocumentBuilder.CurrentSection.AppendContent(s);
    templateDocumentBuilder.MoveTo(templateDocumentBuilder.CurrentSection.Body.LastChild);
    templateDocumentBuilder.InsertBreak(BreakType.SectionBreakNewPage);
}
Node matchedBlockCodeParagraph = args.MatchNode.ParentNode;
matchedBlockCodeParagraph.Remove();

I have 2 documents, i want to insert all sections from 1 document to another at a specific location (args.MatchNode is the location after which i want all the sections to get inserted). How do i achieve this?

@Yajat In your case you should split the target document at the specific node with section break and then insert sections from source document between the section in the target document. For example see the following code:

Document dst = new Document(@"C:\Temp\dst.docx");
DocumentBuilder builder = new DocumentBuilder(dst);

Document src = new Document(@"C:\Temp\src.docx");

// Move document builder to the destination node. For demonstration purposes use bookmark.
builder.MoveToBookmark("test");
// Insert section break.
builder.InsertBreak(BreakType.SectionBreakContinuous);
// Insert section from the source document before the current section.
foreach(Section srcSect in src.Sections)
{
    Node importedSection = dst.ImportNode(srcSect, true, ImportFormatMode.KeepSourceFormatting);
    builder.CurrentSection.ParentNode.InsertBefore(importedSection, builder.CurrentSection);
}

dst.Save(@"C:\Temp\out.docx");
1 Like

This works! Thank you for your help :slight_smile:

1 Like

2 posts were merged into an existing topic: 我怎么给段落指定内容添加背影颜色。