Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
884 views
in Technique[技术] by (71.8m points)

c# - Bookmark to specific page using iTextSharp 4.1.6

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 copied it to add custom bookmarks to non-bookmarked items it fails:

var bookmarks = new ArrayList();
var writer = new PdfCopy(document, memorystream);
// ...
var uni = new Hashtable();
uni.Add("Action", "GoTo");
uni.Add("Title", "Awesome Unicorn pic");
uni.Add("Page", "8 XYZ 0 0 0");
bookmarks.Add(uni);
// ...
writer.Outlines = bookmarks;

But apparently ("Page", "8 XYZ 0 0 0") does not reference Page 8 but rather Section 8 or something like that. Is there an alternative Action I could use to point to an arbitrary page? Or some other method?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...