Hi
Thanks for your inquiry. You can extract contents between two bookmarks and save it in separate Word document. I placed two bookmarks like “start” and “end”.
Please follow up the code snippet:
private void ExtractContent(Document srcDoc, string startBookmark, string endBookmark,string outputFile)
{
//Get start and end bookamerks from source document
Bookmark start = srcDoc.Range.Bookmarks[startBookmark];
Bookmark end = srcDoc.Range.Bookmarks[endBookmark];
//If strat of end bookamrk does not exist in the document then exit from the function
if (start == null || end == null)
return;
//Get first Node in the selection
Node startNode = start.BookmarkStart.ParentNode;
while (startNode.ParentNode.NodeType != NodeType.Body)
startNode = startNode.ParentNode;
//Get last Node in the selection
Node endNode = end.BookmarkStart.ParentNode;
while (endNode.ParentNode.NodeType != NodeType.Body)
endNode = startNode.ParentNode;
//Create new document
Document dstDoc = new Document();
Node currNode = startNode;
//Copy content
while (!currNode.Equals(endNode))
{
Node dstNode = dstDoc.ImportNode(currNode, true,ImportFormatMode.KeepSourceFormatting);
dstDoc.FirstSection.Body.AppendChild(dstNode);
//If next node is null we should move to the next section
if (currNode.NextSibling == null)
{
Section nextSection = (Section)currNode.GetAncestor(NodeType.Section).NextSibling;
currNode = nextSection.Body.FirstChild;
}
else
{
//move to next node
currNode = currNode.NextSibling;
}
}
//Save output document
dstDoc.Save(outputFile);
}
I have attached input/output documents. In case of any ambiguity, please let me know.