簡體   English   中英

如何使用iText7獲取PDF的書簽頁碼

[英]How to get bookmark page number of PDF with iText7

我使用下面的代碼獲取書簽的頁碼,但是返回的頁碼不正確,

var names = pdfDoc.GetCatalog().GetNameTree(PdfName.Dests).GetNames();
var newestBookmark = GetBookmarks(pdfDoc.GetOutlines(false), pdfDoc, names).LastOrDefault();
private static IDictionary<string, int> GetBookmarks(PdfOutline outline, PdfDocument pdfDoc, IDictionary<string, PdfObject> names)
{
    if (outline == null)
    {
        return pdfOutlines;
    }
    var inner = outline.GetAllChildren();
    if (inner != null && inner.Count > 0)
    {
        foreach (var item in inner)
        {
            if (DateTime.TryParse(item.GetTitle(), out DateTime title))
            {                        
                pdfOutlines.Add(item.GetTitle(), pdfDoc.GetPageNumber((PdfDictionary)outline.GetDestination().GetDestinationPage(names)));
            }
            if (item.GetAllChildren() != null && item.GetAllChildren().Count > 0)
            {
                GetBookmarks(item, pdfDoc, names);
            }
        }
    }
    return pdfOutlines;
}

還有其他獲取頁碼的方法嗎?

謝謝

我建議PdfOutline頁面輪廓,使用PdfOutline的子級遍歷層次結構,以便遞歸地遍歷它們。

要按頁對象查找頁碼,應使用pdfDocument.getPageNumber(PdfDictionary).

遍歷輪廓的方法可能如下所示:

void walkOutlines(PdfOutline outline, Map<String, PdfObject> names, PdfDocument pdfDocument) 
{
    if (outline.getDestination() != null) 
    {
        System.out.println(outline.getTitle() + ": page " +
                pdfDocument.getPageNumber((PdfDictionary) outline.getDestination().getDestinationPage(names)));
    }
    for (PdfOutline child : outline.getAllChildren()) 
    {
        walkOutlines(child, names, pdfDocument);
    }
}

調用方法遍歷根的主要入口點:

PdfNameTree destsTree = pdfDoc.getCatalog().getNameTree(PdfName.Dests);
PdfOutline root = pdfDoc.getOutlines(false);
walkOutlines(root, destsTree.getNames(), pdfDoc);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM