iText: Adding web links at an absolute position in Java

A problem I have had to solve recently has been adding links within PDFs. At work we use a private library to create PDFs. This library uses iText (obvious) to work, and one of the users’ requirements is the possibility of having fields that are links to a web site. The links must look like web links (underlined and blue text) and must be positioned in specific places, so absolute positioning is a must.

After searching and trying different solutions, I have finally figured out how to do it. As always, it’s an easy solution.
This code is based on iText 2.1.7, I know there are some new methods that do some of this things in shorter ways, but this version doesn’t have them. First of all I create the link in an underlined and blue font:

// Underlined, courier and 10px font size
Font font = FontFactory.getFont(FontFactory.COURIER, 10, Font.UNDERLINE);
// Blue
font.setColor(0, 0, 255);
// We need a Chunk in order to have a font's style
Chunk chunk = new Chunk("Google", font);
Anchor anchor = new Anchor(chunk);
// Link
anchor.setReference("http://www.google.com");

Then the paragraph is positioned in some coordinates X and Y:

// I take the coordinates from a text field which is defined within a
// PDF template, but you can position the link wherever you want.
float[] coords = form.getFieldPositions("field.name");
// In my case I center the link vertically
float coordY = coords[2] + ((coords[4] - coords[2]) / 2);
// Show the link
// You need to get the PdfContentByte object
// It depends on how you are working with the PDF document
PdfContentByte cb = ... 
ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, anchor, coords[1], coordY, 0);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s