Counting Bookmarks

Let’s assume you have a PDF document, and you want to know how many bookmarks you have in that document, how would you approach that?

The JavaScript API has methods to traverse the bookmark tree. Here is a short program that – once installed in Acrobat’s JavaScript folder – will add a menu item “Count Bookmarks” to the “Document” menu, and when executed will print the number of bookmarks encountered in the JavaScript console.

function CountBookmarks(bkm, nLevel)
{
    var count = 0;
    if (bkm.children != null)
    {
        count = bkm.children.length;
        for (var i = 0; i < bkm.children.length; i++)
        {
             count += CountBookmarks(bkm.children[i], nLevel + 1);
        }
    }

    return count;
}


function DoIt()
{
    console.clear(); console.show();
    var n = CountBookmarks(this.bookmarkRoot, 0);
    console.println("Number of bookmarks found: " + n);
}



// add the menu item
app.addMenuItem({
     cName: "countBookmarks",
     cUser: "Count Bookmarks",
     cParent: "Document",
     cExec: "DoIt();",
     cEnable: "event.rc = (event.target != null);"
});

Save this program in a file in e.g. C:\Program Files\Adobe\Acrobat 9.0\Acrobat\Javascripts (for Acrobat 9) and restart Acrobat. You should now find a new menu item in the Document menu. Load a file with bookmarks in it, and execute the menu item.

I have not implemented the privileged execution context that is required to make this work in all instances, so you have to go into your JavaScript preferences in Acrobat and check the setting for "Enable menu items JavaScript execution privileges":

PreferencesJavaScript.png
This entry was posted in Acrobat, JavaScript, PDF, Programming and tagged , , , . Bookmark the permalink.

3 Responses to Counting Bookmarks

  1. Derek says:

    Thanks for putting together this example after sharing your pointers on twitter. I appreciate it!

  2. Pingback: Create Custom Tools in Adobe Acrobat DC Pro - KHKonsulting LLC

  3. J Murphy says:

    Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *