Free Support Forum -

Create bookmark causing exception

I am trying to enclose a content control (text in content control) inside a bookmark. But I am getting exception saying
Revisions: System.ArgumentException: Cannot insert a node of this type at this location.
at Aspose.Words.CompositeNode.(Node , Node , Boolean )
at Aspose.Words.CompositeNode.InsertBefore(Node newChild, Node refChild)
at DocumentComparison.DocumentComparisonUtil.Convert(String PsDocument

Attached two document
SimpleINDoc (2).zip (1.1 MB)

  1. SimpleINDoc.docx : Causing excpetion for bookmark creation
  2. SimpleINDocPara.docx : Not causing excpetion

Only difference between these documents is first document contains SDT in the body and the second document contains SDT inside Paragraph.

Below is the code I am using for creating bookmark.

                Document LobjDocument = new Document(PsDocument);
                string pdfDocument = PsDocument;
                pdfDocument = pdfDocument.Replace(".docx", ".pdf");
                DocumentBuilder builder = new DocumentBuilder(LobjDocument);
                NodeCollection nodes = LobjDocument.GetChildNodes(NodeType.StructuredDocumentTag, true);
                int iCount = nodes.Count;
                foreach (StructuredDocumentTag sdt in nodes)
                    Debug.WriteLine("Bookmark : " + sdt.Tag);

                    BookmarkStart start = builder.StartBookmark(sdt.Tag);
                        BookmarkEnd end = builder.EndBookmark(sdt.Tag);
                        sdt.ParentNode.InsertBefore(start, sdt);
                        sdt.ParentNode.InsertAfter(end, sdt);
              PdfSaveOptions options = new PdfSaveOptions();
              options.OutlineOptions.DefaultBookmarksOutlineLevel = 9;
              LobjDocument.Save(pdfDocument, options);


Thanks for your inquiry. You are inserting same bookmark twice in your code. Once using StartBookmark and EndBookmark method and second time by using InsertBefore and InsertAfter methods.

Regarding the exception, some content controls are block level nodes in your document and bookmark cannot be inserted at this level. We suggest you please read following article.
Aspose.Words Document Object Model

The BookmarkStart and BookmarkEnd nodes are inline level nodes. You need to move the cursor to the first child node of content control and insert the bookmark. Hope this helps you.