7
votes

I've not had any luck in either the OpenXML API or Word/VSTO API, finding a way to create or modify a bookmark's visibility. Even adding bookmarks manually in Word, there's no box to check to make the bookmark hidden. Although there is a checkbox in the Bookmarks dialog that lets you show hidden bookmarks. So how are hidden bookmarks represented in the XML, and can you create them using the Open XML SDK? Or are they a legacy thing that MS no longer wants us to create?

2
Your name ("System.Cats.Lol") is my favorite ever on SO.Carl G

2 Answers

15
votes

OK so this is easier than I thought...you just precede the bookmark name with an underscore. Note that this can only be done programmatically, not when adding bookmarks manually in Word.

Iiiiiiiiinteresting....

Update: Another thing I found--before you can iterate or access hidden bookmarks in a Bookmarks object, you must set its ShowHidden property to true.

PS - SO, if you have any control over your spelling dictionary, you might add "programmatically". Unless I'm spelling it wrong. :)

0
votes

I created normal bookmarks in word file and than converted them to hidden bookmark pragmatically. As said above hidden bookmarks can only be created pragmatically and their name precede by "_". When ever iterating the bookmarks list make sure Bookmarks.ShowHidden is set to true, otherwise hidden bookmarks will not show up in the list. Below is the code that I used to hide all the visible bookmarks. At the very end I also clear undo record to make sure user can not undo the changes I made. You may create the custom undo record delete the last action if you wish.

public static void hideAllBookmark(Document doc)
{
    String newName = null;
    Range newRange = null;
    bool backup = doc.Bookmarks.ShowHidden;
    doc.Bookmarks.ShowHidden = false;

    for (int i = doc.Bookmarks.Count; i > 0; i--)
    {
        if (!doc.Bookmarks[i].Name.Substring(0, 1).Equals("_", StringComparison.OrdinalIgnoreCase))
        {
            newName= "_" + doc.Bookmarks[i].Name;
            newRange = doc.Bookmarks[i].Range;
            doc.Bookmarks[i].Delete();
            doc.Bookmarks.Add(newName, newRange);
        }
    }
    doc.Bookmarks.ShowHidden = backup;
    doc.UndoClear();
}