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 + ((coords - coords) / 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, coordY, 0);