Java: Reading PDF bookmark names with itext

回眸只為那壹抹淺笑 提交于 2019-12-25 01:55:48

问题


I am working with a single PDF containing multiple documents. Each document has a bookmark. I need to read the bookmark names for a reconciliation application that I am building. The code below is not working for me. I am trying to place the bookmark name in the title string. Can anyone provide any guidance? Thank you very much.

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

for(int i = 0; i < bookmarks.size(); i++){

    HashMap<String, Object> bm = bookmarks.get(i);
    String title = ((String)bm.get("Title"));

}

回答1:


You are not taking into account that bookmarks are stored in a tree structure with branches and leaves (in the PDF specification, it's called the outline tree).

As @Todoy says in the comment section, your code works for the top-level, but if you want to see all the titles, you need to use a recursive method that also looks at the "Kids".

Take a look at this code sample:

public void inspectPdf(String filename) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(filename);
    List<HashMap<String,Object>> bookmarks = SimpleBookmark.getBookmark(reader);
    for (int i = 0; i < bookmarks.size(); i++){
        showTitle(bookmarks.get(i));
    }
    reader.close();
}

public void showTitle(HashMap<String, Object> bm) {
    System.out.println((String)bm.get("Title"));
    List<HashMap<String,Object>> kids = (List<HashMap<String,Object>>)bm.get("Kids");
    if (kids != null) {
        for (int i = 0; i < kids.size(); i++) {
            showTitle(kids.get(i));
        }
    }
}

The showTitle() method is recursive. It calls itself if an examined bookmark entry has kids. With this code snippet, you can walk through all the branches and leaves of the outline tree.



来源:https://stackoverflow.com/questions/28634172/java-reading-pdf-bookmark-names-with-itext

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!