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

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 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.

Once you have an instance of PdfAnnotation, you can add it to a specific page using the addAnnotation() method.


Share this article

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now