Copy the content of bookmark into another document including SectionBreaks?

Hi, Our product is currently copy/merge the content of bookmark(nodes) into another document.
But the problem is our current code couldn’t handle the situation where the content of bookmark has SectionBreak inside, as the ‘NextSibling’ property for nodes in bookmark content would be null before SectionBreak.

What are recommended ways of doing that; insert contents including SectionBreaks or PageBreaks?

I also attached two documents(destination and inserting document) to illustrate the case we want to handle in our case.

Hi Doug,

Thanks for your inquiry.

I suggest you please read the following documentation link for your kind reference.
https://docs.aspose.com/words/net/how-to-extract-selected-content-between-nodes-in-a-document/
https://docs.aspose.com/words/java/insert-and-append-documents/

Bookmark class represents a single bookmark. Bookmark is a “facade” object that encapsulates two nodes BookmarkStart and BookmarkEnd in a document tree and allows to work with a bookmark as a single object.

The ExtractContent method shared in above documentation link does not extract the section breaks. In this case, I suggest you following solution. Hope this helps you.

  1. Insert the bookmark at the end of each section break with name starts with ‘BM_Break’.
  2. After extracting contents, insert the document into another document (in your case, Including+document.docx)
  3. Insert the section breaks at the place of inserted bookmark.

Please check the following code example for your kind reference. Hope this helps you.

// Load in the document
Document doc = new Document(MyDir + "Insert.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
int bm = 1;
foreach (Section section in doc.Sections)
{
    if (doc.FirstSection == section)
        continue;
    builder.MoveTo(((Section)section.PreviousSibling).Body.LastParagraph);
    if (section.PageSetup.SectionStart == SectionStart.Continuous)
    {
        builder.StartBookmark("BM_BreakC" + bm);
        builder.EndBookmark("BM_BreakC" + bm);
    }
    if (section.PageSetup.SectionStart == SectionStart.NewPage)
    {
        builder.StartBookmark("BM_BreakNewPage" + bm);
        builder.EndBookmark("BM_BreakNewPage" + bm);
    }
    bm++;
}
// Retrieve the bookmark from the document.
Aspose.Words.Bookmark bookmark = doc.Range.Bookmarks["ToBeInserted"];
// We use the BookmarkStart and BookmarkEnd nodes as markers.
BookmarkStart bookmarkStart = bookmark.BookmarkStart;
BookmarkEnd bookmarkEnd = bookmark.BookmarkEnd;
// Firstly extract the content between these nodes including the bookmark. 
ArrayList extractedNodesInclusive = ExtractContent(bookmarkStart, bookmarkEnd, true);
// Generate the documnt with extracted contents.
Document dstDoc = GenerateDocument(doc, extractedNodesInclusive);
// Load the document
Document doc2 = new Document(MyDir + "Including+document.docx");
DocumentBuilder newbuilder = new DocumentBuilder(doc2);
newbuilder.MoveToBookmark("InsertingLocation");
// Insert document
InsertDocument(newbuilder.CurrentParagraph, dstDoc);
foreach (Bookmark bmark in doc2.Range.Bookmarks)
{
    if (bmark.Name.Contains("BM_BreakC"))
    {
        newbuilder.MoveTo(bmark.BookmarkEnd);
        newbuilder.InsertBreak(BreakType.SectionBreakContinuous);
        bmark.Remove();
    }
    else if (bmark.Name.Contains("BM_BreakNewPage"))
    {
        newbuilder.MoveTo(bmark.BookmarkEnd);
        newbuilder.InsertBreak(BreakType.SectionBreakNewPage);
        bmark.Remove();
    }
}
doc2.Range.Bookmarks["InsertingLocation"].Text = "";
doc2.Range.Bookmarks["InsertingLocation"].Remove();
doc2.Save(MyDir + "Out.docx");

Thank you Tahir Manzoor, using the code from you to find section break and insert them latter. I solved my issue!

However, for the following documents I provided, the second section break will be missing. It seems that after ‘bmark.Remove()’ line, the bookmark (BM_BreakC2’ next the removed bookmark (BM_BreakC1) will not be retrieved and checked in the next iteration of foreach, and I ended up have one less section break.

Hi Doug,

Thanks for your inquiry. Please use the following code example to achieve your requirements. Please check the InsertDocumentWithSectionFormatting method from here:
https://docs.aspose.com/words/java/insert-and-append-documents/

Hope this helps you.

Document doc = new Document(MyDir + "TestIncludeWithBreakInsert.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
builder.StartBookmark("bm_remove");
Bookmark bookmark = doc.Range.Bookmarks["ToBeIncluded"];
BookmarkStart bookmarkStart = bookmark.BookmarkStart;
BookmarkEnd bookmarkEnd = bookmark.BookmarkEnd;
// Remove contents before and after bookmark ToBeIncluded
builder.MoveTo(bookmarkStart);
builder.EndBookmark("bm_remove");
doc.Range.Bookmarks["bm_remove"].Text = "";
doc.Range.Bookmarks["bm_remove"].Remove();
builder.MoveTo(bookmarkEnd);
builder.StartBookmark("bm_remove");
builder.MoveToDocumentEnd();
builder.EndBookmark("bm_remove");
doc.Range.Bookmarks["bm_remove"].Text = "";
doc.Range.Bookmarks["bm_remove"].Remove();
Document docDest = new Document(MyDir + "TestIncludeWithBreak.docx");
docDest.LastSection.PageSetup.SectionStart = SectionStart.Continuous;
DocumentBuilder newbuilder = new DocumentBuilder(docDest);
newbuilder.MoveToBookmark("ToIncluding");
docDest.Range.Bookmarks["ToIncluding"].Text = "";
// Insert document
InsertDocumentWithSectionFormatting(newbuilder.CurrentParagraph, doc);
docDest.Save(MyDir + "Out.docx");

Hi Tahir Manzoor,

Thank you for the update. I did test this new approach, it doing what’s supposed to do. However, there is a small issue that it adds two extra section breaks at the beginning and end of the inserted paragraph.

I fixed it by calling this new function I wrote twice at the end of the InsertDocumentWithSectionFormatting, obviously, I have to pass the right section references as parameters so it can working properly:

private static void SafeRemoveSectionBreak(Section sectionBefore, Section sectionAfter)
{
    var tempSection = sectionAfter;
    sectionAfter.Remove();
    sectionBefore.AppendContent(tempSection);
}

Also, the previous approach you provided seems working fine with us as We don’t need the code to remove bookmark inside a foreach loop (we have our own separated method to remove bookmarks based on configuration. Out of those two approaches, which one is recommended?

Hi Doug,

Thanks for your inquiry. Yes, InsertDocumentWithSectionFormatting method inserts the section break before and after the inserted contents. It is nice to hear from you that you have found the solution to remove these section breaks.

In your case, I suggest you to use second approach used in this post. Please let us know if you have any more queries.

Hi Tahir Manzoor,

May I ask why the second one is recommended? I can see its more generic in term of handle different section break type, but it seems to me that the first approach should do the same once I added cases to handle Odd and Even Section breaks, and of course if I do not remove the bookmark inside the foreach loop. Then I would expected that they behave same?

Hi Doug,

Thanks
for your inquiry. You can use both approaches to achieve your requirements. In first approach there are more steps to achieve your requirements. See below:

  1. Insert bookmarks for different section break types. You also need to add bookmarks for SectionBreakEvenPage and SectionBreakOddPage types.
  2. Extract contents and generate new document
  3. Insert section breaks of the same types
  4. Inserted document. In this case, the inserted document might not be same.

The second approach insert bookmarks before and after selected contents and remove them. This approach is small and fast. In this approach, the section breaks are exactly same as these are in original document because section breaks are not removed from document.

However, you can use one of two approaches which is suitable for you. Please let us know if you have any more queries.

No more questions from me for now, thank you Tahir Manzoor!

Hi there,

Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.