11 Mar 2009

Counting Bookmarks

Posted by khk

Please visit the same post on my business site. The comments are closed here, so if you want to comment, you have to head over to http://khkonsulting.com/2009/03/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

Subscribe to Comments

One Response to “Counting Bookmarks”

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

     

    Derek