none
Inserting Bookmark into document header/footer RRS feed

  • Question

  • Hello All,

    Currently we have a word add in created - which will insert bookmarks into the word document. Later the bookmarks will be replaced with the value for the bookmark.

    The issue what I am facing is with respect insert placeholder into the document. Inserting placeholder works fine as expected when bookmark is inserted any where in the body of the document; but if a bookmark is inserted in header/footer - its not working as expected. Whenever I try to select  the bookmark inserted into Header/Footer through automatically - it will not select the bookmark in the header - it will select some other start and end(i,e, Range)

    Here is the code snippet which is used to insert place holder:

    Insert Placeholder

     

    string placeholderDisplayText = “some_text”;

     object start = Application.Selection.End;

     

    Application.Selection.InsertAfter(placeholderDisplayText);

     

    object end = placeholderDisplayText.Length + (int)start;

    object range = Application.ActiveDocument.Range(ref start, ref end);

    Application.ActiveDocument.Bookmarks.Add(BookmarkHelper.GenerateKeyFromGuid(placeholder.Id), ref range);

     

    However when I get a reference to the bookmark inserted and call bookmark.Select(), it select some other region than the bookmark text.

    What is interesting is - the same thing works fine when we insert bookmark manually using the Bookmark button in the Insert tab.

     

    Do you have any idea on whats wrong the above code and why its not working as expected when a bookmark in inserted into header/footer.

     

    Thanks in advance,

    Ranganatha H C


     


    Monday, July 4, 2011 12:33 PM

Answers

  • Hi Ranganatha

    It's difficult to tell from your description exactly what it is you want to do. What's clear, however, is that you're working with Select and Selection, and that's not a good idea. Much better is to work with the RANGE object. So if you want to put text "at" the bookmark:

    Application.ActiveDocument.get_Bookmark(ref oBookmarkName).Range.Text = "The text";

    If the bookmark contains text, so that it looks like [this] then the above action will delete the bookmark. If you want to retain the bookmark in this situation, then you have to do something more like (pseudocode):

    Word.Range rngBookmark = Application.ActiveDocument.get_Bookmark(ref oBookmarkName).Range;
    rngBookmark.Text = "The text";
    object oRngBookmark = rngBookmark;
    Application.ActiveDocument.Bookmarks.Add(BookmarkName, ref oRngBookmark);

    Which will recreate the bookmark around the text inserted into the range.


    Cindy Meister, VSTO/Word MVP
    Monday, July 4, 2011 1:21 PM
    Moderator