How can I create bookmarks with a JS script in Adobe Acrobat?

233 Views Asked by At

I have a huge PDF (2000+ pages, here is a sample of the document) that lost it's tags and bookmarks. I cannot contact the original source.

What I'm trying to do is run a JS script on Adobe Acrobat that generates bookmarks to allow easier navigation through the document.

This is what I have tried so far:

// Function to create bookmarks for titles and subtitles
function createBookmarks() {
    const numPages = this.numPages;
    const bookmarks = [];
    let currentTitleBookmark = null;

    for (let pageNum = 0; pageNum < numPages; pageNum++) {
        const pageText = this.getPageNumWords(pageNum);
        let titleMatch, subtitleMatch;

        for (let i = 0; i < pageText.length; i++) {
            const word = pageText[i];
            const text = word.text;

            // Check if the text matches the title pattern (e.g., "1 Title")
            titleMatch = text.match(/^(\d+)\s(.+)$/);
            if (titleMatch) {
                const titleLevel = titleMatch[1];
                const titleName = titleMatch[2];
                const bookmark = this.bookmarkRoot.createChild(titleName);
                bookmarks.push({ level: titleLevel, bookmark });
                currentTitleBookmark = bookmark;
            }

            // Check if the text matches the subtitle pattern (e.g., "1.1 Subtitle")
            subtitleMatch = text.match(/^(\d+\.\d+)\s(.+)$/);
            if (subtitleMatch && currentTitleBookmark) {
                const subtitleName = subtitleMatch[2];
                const subtitleBookmark = currentTitleBookmark.createChild(subtitleName);
                bookmarks.push({ level: subtitleMatch[1], bookmark: subtitleBookmark });
            }
        }
    }

    // Set the initial bookmark to open
    if (bookmarks.length > 0) {
        bookmarks[0].bookmark.dest = pageNum;
    }
}

// Call the function to create bookmarks
createBookmarks();

When I press Ctrl + Enter in the console in line with the last line of code an error shows up saying:

ReferenceError: createBookmarks is not defined 
1:Console:Exec
undefined

What am I missing?

0

There are 0 best solutions below