How to create a clickable polygon or path?

Tags: annotationslink annotationpolygonquadpointsiText 5

Is anyone out there able to create a clickable annotation that has an irregular shape?

I know I can create a rectangular one like this

float x1 = 100, x2 = 200, y1 = 150, y2 = 200;
iTextSharp.text.Rectangle r = new iTextSharp.text.Rectangle(x1, y1, x2, y2);
PdfName pfn = new PdfName(lnk.LinkID.ToString());
PdfAction ac = new PdfAction(lnk.linkUrl, false);
PdfAnnotation anno = PdfAnnotation.CreateLink(stamper.Writer, r, pfn, ac);
int page = 1;
stamper.AddAnnotation(anno, page);
Is there any way to do that with a graphics path?

Posted on StackOverflow on Nov 22, 2014 by ksliman

The secret ingredient you are looking for is called QuadPoints ;-)

Allow me to explain how QuadPoints are used by showing you the AddPolygonLink example.

First let's take a look at some code that constructs and draws a path:

canvas.moveTo(36, 700);
canvas.lineTo(72, 760);
canvas.lineTo(144, 720);
canvas.lineTo(72, 730);

I am using this code snippet only to show the irregular shape that we'll make clickable.

You already know how to create a clickable link with a rectangular shape:

Rectangle linkLocation = new Rectangle(36, 700, 144, 760);
PdfDestination destination = new PdfDestination(PdfDestination.FIT);
PdfAnnotation link = PdfAnnotation.createLink(stamper.getWriter(),
    linkLocation, PdfAnnotation.HIGHLIGHT_INVERT,
    1, destination);

This corresponds with the code snippet you already provided in your question.

Now let's introduce some QuadPoints:

PdfArray array = new PdfArray(new int[]{72, 730, 144, 720, 72, 760, 36, 700});
link.put(PdfName.QUADPOINTS, array);

According to ISO-32000-1, QuadPoints are:

An array of 8 × n numbers specifying the coordinates of n quadrilaterals in default user space that comprise the region in which the link should be activated. The coordinates for each quadrilateral are given in the order

x1 y1 x2 y2 x3 y3 x4 y4

specifying the four vertices of the quadrilateral in counterclockwise order. For orientation purposes, such as when applying an underline border style, the bottom of a quadrilateral is the line formed by (x1, y1) and (x2, y2).

If this entry is not present or the conforming reader does not recognize it, the region specified by the Rect entry should be used. QuadPoints shall be ignored if any coordinate in the array lies outside the region specified by Rect.

Note that I defined the linkLocation parameter in such a way that the irregular shape fits inside that rectangle.

Caveat: you can try this functionality by testing this example: link_polygon.pdf, but be aware that while this will work when viewing the file in Adobe Reader, this may not work with inferior PDF viewers that did not implement the QuadPoints functionality.