使用 iText 库在 PDF 中生成分层书签

Hierarchical Bookmark Generation in PDF using iText library

我在 ArrayList 中有如下数据:

static ArrayList<DTONodeDetail> tree;
public static void main(String[] args) {
    // TODO Auto-generated method stub
    tree=new ArrayList<DTONodeDetail>();

     //first argument->NodeId
     //second->NodeName
     // third -> ParentNodeId

    tree.add(getDTO(1,"Root",0));
    tree.add(getDTO(239,"Node-1",1));
    tree.add(getDTO(242,"Node-2",239));
    tree.add(getDTO(243,"Node-3",239));
    tree.add(getDTO(244,"Node-4",242));
    tree.add(getDTO(245,"Node-5",243));
    displayTree(tree.get(0));       

}

public static DTONodeDetail getDTO(int nodeId,String nodeName,int parentID)
{
    DTONodeDetail dto=new DTONodeDetail();
    dto.setNodeId(nodeId);
    dto.setNodeDisplayName(nodeName);
    dto.setParentID(parentID);

    return dto;
}

我可以在 tree structure 中显示以上数据,如下所示:

Root
-----Node-1
------------Node-2
------------------Node-4
------------Node-3
------------------Node-5

我尝试使用 itext 库的 Chapter class,但不知道如何生成分层书签。

我的问题是我可以使用 itext java library 在 pdf 中创建分层书签(如上)吗?

在 PDF 术语中,书签被称为 大纲。请看一下 CreateOutline example from my book to find out how to create an outline tree as shown in this PDF: outline_tree.pdf

我们从树的根开始:

PdfOutline root = writer.getRootOutline();

然后我们添加一个分支:

PdfOutline movieBookmark = new PdfOutline(root, 
            new PdfDestination(
                PdfDestination.FITH, writer.getVerticalPosition(true)),
            title, true);

给这个分支,我们添加一个叶子:

PdfOutline link = new PdfOutline(movieBookmark,
            new PdfAction(String.format(RESOURCE, movie.getImdb())),
            "link to IMDB");

以此类推

关键是在构建child大纲时,使用PdfOutline并传递parent大纲作为参数。

根据评论更新:

还有一个名为 BookmarkedTimeTable 的示例,其中我们以完全不同的方式创建大纲树:

ArrayList<HashMap<String, Object>> outlines = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map = new HashMap<String, Object>();
outlines.add(map);

在这种情况下,map 是我们可以添加分支和叶子的根 object。完成后,我们将大纲树添加到 PdfStamper,如下所示:

stamper.setOutlines(outlines);

请注意,PdfStamper 是我们在操作现有 PDF 时需要的 class(与我们从头开始创建 PDF 时要使用的 PdfWriter 相对)。

基于另一条评论的补充更新:

要创建层次结构,您只需添加孩子。

一级:

HashMap<String, Object> calendar = new HashMap<String, Object>();
calendar.put("Title", "Calendar");

二级:

HashMap<String, Object> day = new HashMap<String, Object>();
day.put("Title", "Monday");
ArrayList<HashMap<String, Object>> days = new ArrayList<HashMap<String, Object>>();
days.add(day);
calendar.put("Kids", days);

第三级:

HashMap<String, Object> hour = new HashMap<String, Object>();
hour.put("Title", "10 AM");
ArrayList<HashMap<String, Object>> hours = new ArrayList<HashMap<String, Object>>();
hours.add(hour);
day.put("Kids", hours);

等等...