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?
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 PdfStamper
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:
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
Rectangle linkLocation = new Rectangle(523, 770, 559, 806);
PdfDestination destination = new PdfDestination(PdfDestination.FIT);
PdfAnnotation link = PdfAnnotation.createLink(stamper.getWriter(),
linkLocation, PdfAnnotation.HIGHLIGHT_INVERT,
3, destination);
link.setBorder(new PdfBorderArray(0, 0, 0));
stamper.addAnnotation(link, 1);
stamper.close();
The link
object is created using:
- the
writer
instance tied to the stamper
,
- the rectangle (the position you say you know in advance,
- a highlighting option (pick one: HIGHLIGHT_NONE, HIGHLIGHT_INVERT, HIGHLIGHT_OUTLINE, HIGHLIGHT_PUSH, HIGHLIGHT_TOGGLE),
- the page you want to link to,
- a destination (different options are possible, see The ABC of PDF).
Once you have an instance of PdfAnnotation
, you can add it to a specific page using the addAnnotation()
method.