How to remove bookmark WITH content (including nested stuff)

Even after adding remove…?

@Raghul214 Could you please clarify, after adding remove of what?

I am using bookmark.Remove()

@Raghul214 Yes, everything works as expected even after removing the bookmark. Here is the modified code and the output:

string bookmarkName = "BM4";

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

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

Bookmark bookmark = src.Range.Bookmarks[bookmarkName];
var extractedNodes = ExtractContentHelper.ExtractContent(bookmark.BookmarkStart, bookmark.BookmarkEnd, true);
var extractedContent = ExtractContentHelper.GenerateDocument(src, extractedNodes);

// Remove old content from the destination document.
dst.Range.Bookmarks[bookmarkName].Text = "";
builder.MoveToBookmark(bookmarkName, true, true);
builder.InsertDocumentInline(extractedContent, ImportFormatMode.UseDestinationStyles, new ImportFormatOptions());
dst.Range.Bookmarks[bookmarkName].Remove();

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

out.docx (22.3 KB)

dst.Range.Bookmarks[bookmarkName].Remove();

adding this after insertion will remove the boomark na…?

Before insertion I want to make sure all content is removed

@Raghul214 Bookmark.Remove does not remove the bookmark’s content. This method removes only the bookmark itself. If it is required to remove the bookmark’s content, you should simple set the bookmark’s text to empty string as shown in the code example above. But again, you should make sure the bookmarks wraps the content properly, because there might be peculiarities when bookmark start in the table for example and ends outside the table.

Ok if I bookmark before table and end after table and using bookmark.Text=“” the entire table will be removed…?
Also if i have image will thai work…?

@Raghul214 Yes, setting bookmark’s text to empty string will work in most possible cases.

1 Like

Ok then that should be fine thank you. Let me try and update u

1 Like