Sunday, October 28, 2012

PDF Bookmarks Reader

NOTE: Requires iText jar

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.SimpleBookmark;

public class BookmarkFetcher {

    public static void main(String[] args) throws IOException {

        PdfReader reader = new PdfReader("C:\\abc.pdf");
        List<HashMap<String, Object>> list = SimpleBookmark.getBookmark(reader);

        for (Iterator<HashMap<String, Object>> i = list.iterator(); i.hasNext();) {
            showBookmark((Map<String, Object>) i.next());
        }
    }

    @SuppressWarnings("unchecked")
    private static void showBookmark(Map<String, Object> bookmark) {

        System.out.println(bookmark.get("Title").toString());

        ArrayList<Object> kids = (ArrayList<Object>) bookmark.get("Kids");

        if (kids == null)
            return;

        for (Iterator<Object> i = kids.iterator(); i.hasNext();) {
            showBookmark((Map<String, Object>) i.next());
        }
    }
}
Output:
Displays bookmars from the pdf passed.