更改PDF文件中儿童轮廓的缩放

时间:2017-04-24 13:03:55

标签: c# pdf recursion itext

我想更改PDF文件中书签(轮廓)的缩放。我已经完成了父母书签,但我不知道如何为kids做到这一点。我可以阅读“孩子们”#39;但是我很难实现递归来改变非父书签的缩放。我非常感谢有关如何解决问题的建议。 我的代码(工作正常):

var bookmarks = SimpleBookmark.GetBookmark(reader);
var newBookmarks = new List<Dictionary<string, object>>();

for (int i = 0; i < bookmarks.Count; i++)
{
    string zoomValue = "1.25";

    if (bookmarks[i]["Title"].ToString() == "Cover" ||
        bookmarks[i]["Title"].ToString() == "C")
    {
        zoomValue = "1";
    }

    int pageNumber = Int32.Parse(bookmarks[i]["Page"]
        .ToString().Split(' ')[0]);
    // increase pageHight by one to have a nicer zoom
    float pageHeight = reader.GetPageSize(pageNumber).Height + 1;
    string replaceValue = $"{pageNumber} XYZ 0 {pageHeight} {zoomValue}";
    newBookmarks.AddRange(ChangeZoom(bookmarks, i, replaceValue));

}

private static IList<Dictionary<string, object>>
    ChangeZoom(IList<Dictionary<string, object>> bookmarks, int i, string replaceValue)
{
    bookmarks[i]["Page"] = replaceValue;
    if (bookmarks[i].ContainsKey("Kids"))
    {
        var kids = (List<Dictionary<string, object>>)bookmarks[i]["Kids"];
        // recursion here?
    }
    return bookmarks;
}

1 个答案:

答案 0 :(得分:0)

我不熟悉iText框架,但如果您只需要将replaceValue设置为所有子书签,您可以这样做:

public void Meth(PdfReader reader)
{
    foreach (var prntBookmark in SimpleBookmark.GetBookmark(reader))
    {
        ChangeZoom(prntBookmark, reader);           
    }
}
private static void ChangeZoom(Dictionary<string, object> bookmark, PdfReader reader)
{
    string zoomValue = "1.25";

    if (bookmark["Title"].ToString() == "Cover" ||
    bookmark["Title"].ToString() == "C")
    {
        zoomValue = "1";
    }

    int pageNumber = Int32.Parse(bookmark["Page"].ToString().Split(' ')[0]);
    // increase pageHight by one to have a nicer zoom
    float pageHeight = reader.GetPageSize(pageNumber).Height + 1;
    bookmark["Page"] = $"{pageNumber} XYZ 0 {pageHeight} {zoomValue}";

    if (bookmark.ContainsKey("Kids"))
    {
        (bookmark["Kids"] as List<Dictionary<string, object>>)?.ForEach(bm=>ChangeZoom(bm, reader));
    }
}

...

(bookmark["Kids"] as List<Dictionary<string, object>>)?.ForEach(bm=>ChangeZoom(bm, reader));

相同
var kidBookmarks =(bookmark["Kids"] as List<Dictionary<string, object>>);
foreach (var bm in kidBookmarks)
        {
            ChangeZoom(bm, reader);         
        }

这种方式可以递归遍历所有子书签并更改缩放。