How to create a link to a specific page number?

Tags: annotationslink annotationgo to pageiText 7

I know how to target any text of any PDF page using code:

Anchor click = new Anchor("Click to go to Target");
click.Reference = "#target";
Paragraph p1 = new Paragraph();
p1.Add(click);
doc.Add(p1);
Anchor target = new Anchor("Target");
target.Name = "target";
doc.Add(target);
My question is how to target a page based on its number. For example if targeted page number is 6, clicking on the Anchor text should take to 6th page.

Posted on StackOverflow on Feb 20, 2014 by Yogesh

In iText 7 you have two possible ways to set a link to a page.

Example 1:

Paragraph anchor = new Paragraph("This is a destination");
anchor.setProperty(Property.DESTINATION, "dest1"); 
doc.add(anchor);
 
Paragraph chunk = new Paragraph(new Link("Link", PdfAction.createGoTo("dest2")));

Example 2:

PdfArray array = new PdfArray();
array.add(doc.getPdfDocument().getPage(1).getPdfObject());
array.add(PdfName.Fit);
PdfDestination dest2 = PdfDestination.makeDestination(array);
 
Paragraph chunk = new Paragraph(new Link("Link", PdfAction.createGoTo("dest2")));

Click this link if you want to see how to answer this question in iText 5.