We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

DocumentBuilder InsertHtml throws NullReferenceException

Hi,
after updating to the latest version 22.2.0 of Aspose.Words I get a System.NullReferenceException when inserting HTML into a bookmark with the DocumentBuilder. It seems that the CurrentSection throws the exception. If I remove the paragraph from the bookmark the exception does not occur.

Here’s the relevant code snippet:

var values = new Dictionary<string, string>
            {
                { "Text_manuell", "<p>Hello World</p>" }
            };

var builder = new DocumentBuilder(document);

foreach (var pair in values)
{
    var bookmark = document.Range.Bookmarks[pair.Key];

    builder.MoveToBookmark(bookmark.Name);
    bookmark.Text = string.Empty;
    bookmark.Remove();
    builder.InsertHtml(pair.Value, true);
}

Is it a bug? How can I fix it? The word document is attachted
bookmark test.docx (16.6 KB)

@jan.net The problem occurs because in your code you move the DocumentBuilder cursor to the bookmark and immediately remove the bookmark and its content. In this case DocumentBuilder's cursor hangs on the removed node… To fix the problem you can change the code like this:

var bookmark = document.Range.Bookmarks[pair.Key];
bookmark.Text = string.Empty;
                
builder.MoveToBookmark(bookmark.Name);
builder.InsertHtml(pair.Value, true);

bookmark.Remove();

@alexey.noskov
thanks, works again now.
I’m just a little confused why it worked at all before.

@jan.net It is perfect that code works now. Most likely the code worked before because bookmarks in your documents were empty. In this case DocumentBuilder is moved to the BookmarkEnd. If the bookmark is not empty DocumentBuilder is moved to the Run inside bookmark to properly handle formatting applied to the text inside the bookmark.