How to insert a "linked rectangle" with iText?
I want to insert a hyperlink into an existing PDF at a position I know in advance: I already have the coordinates of a rectangle on a given page. I want to link this rectangle to another page of the same PDF (which I also know in advance). How do I achieve this?
Posted on StackOverflow on Nov 7, 2013 by Hans Stricker
Please take a look at the AddLinkAnnotation example.
As you (should) already know (but you didn't show what you've already tried, which is kind of mandatory on StackOverflow), you can use PdfDocument
to manipulate an existing PDF. Adding a rectangular link on one page to another page, is as simple as adding a link annotation to that page:
PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
Rectangle linkLocation = new Rectangle(523, 770, 36, 36);
int[] borders = {0, 0, 1};
PdfAnnotation annotation = new PdfLinkAnnotation(linkLocation)
.setHighlightMode(PdfAnnotation.HIGHLIGHT_INVERT)
.setAction(PdfAction.createGoTo(PdfExplicitDestination.createFit(3)))
.setBorder(new PdfArray(borders));
pdfDoc.getFirstPage().addAnnotation(annotation);
pdfDoc.close();
The link
object is created using:
the rectangle (the position you say you know in advance),
a highlighting mode (pick one:
HIGHLIGHT_NONE
,HIGHLIGHT_INVERT
,HIGHLIGHT_OUTLINE
,HIGHLIGHT_PUSH
,HIGHLIGHT_TOGGLE
),a destination,
the page you want to link to.
Once you have an instance of PdfAnnotation
, you can add it to a specific page using the addAnnotation()
method.
Click this link if you want to see how to answer this question in iText 5.