Bookmark to specific page using iTextSharp 4.1.6

后端 未结 1 1226
小蘑菇
小蘑菇 2021-01-21 19:08

I want to add a bookmark pointing to a specific page within a document. Adding bookmarks from other PDF files I\'m merging with code similar to that below works fine, but when I

相关标签:
1条回答
  • 2021-01-21 19:16

    Looks like the PDF coordinate system messed with my feeble human brain. Turns out that ("Page", "8 XYZ 0 0 0"); actually does reference page 8, but "XYZ 0 0 0" does not reference the top left point on a page, but rather the bottom left point. So when clicked, a bookmark like this unexpectedly takes you to page two. Awesome.

    The code below works as expected, because it gets the height of the first page and uses that to link to the top of the page. The code is gathered from different places around my source, so it's not very "together" but still, it works.

    var bookmarks = new ArrayList();
    var rdr = new PdfReader(first);
    var doc = new Document(rdr.GetPageSizeWithRotation(1));
    var wri = new PdfCopy(doc, memorystream);
    var temp = wri.GetImportedPage(rdr, 1); // get 1st page
    var h = temp.Height; // get height of 1st page
    
    // Add first item to bookmarks.
    var test = new Hashtable();
    test.Add("Action", "GoTo");
    test.Add("Title", "Page1 0 H 0");
    test.Add("Page", "1 XYZ 0 "+h+" 0"); // use height of 1st page
    bookmarks.Add(test);
    
    // Do your worst and afterwards set the bookmarks to Outline. So yeah.
    wri.Outlines = bookmarks;
    
    0 讨论(0)
提交回复
热议问题