In this post, I am going to show you how to Add Hyper Links to cells in a table.
Following snippet add hyper links to a table.
private Static Void addHyperLink(PdfPTable table, String title, String link) {
Phrase phrase = new Phrase();
Chunk chunk = new Chunk(title);
chunk.setAnchor(link);
phrase.add(chunk);
table.addCell(phrase);
}
Following is the complete working application.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class TestTable {
private static final String fileName = "/Users/harikrishna_gurram/Documents/itext/tableEx.pdf";
private static Font font = FontFactory.getFont(FontFactory.TIMES_ROMAN, 15, Font.BOLD, BaseColor.RED);
private static void addHyperLink(PdfPTable table, String title, String link) {
Phrase phrase = new Phrase();
Chunk chunk = new Chunk(title);
chunk.setAnchor(link);
phrase.add(chunk);
table.addCell(phrase);
}
public static void main(String args[]) throws DocumentException, MalformedURLException, IOException {
/* Create parent directories to destination pdf file */
File file = new File(fileName);
file.getParentFile().mkdirs();
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(fileName));
document.open();
PdfPTable table = new PdfPTable(1);
table.addCell(new Phrase("My Tutorials", font));
addHyperLink(table, "Java Tutorial", "http://self-learning-java-tutorial.blogspot.in");
addHyperLink(table, "MongoDB Tutorial",
"http://self-learning-java-tutorial.blogspot.in/2016/05/mongodb-home.html");
addHyperLink(table, "R Tutorial for beginners",
"http://self-learning-java-tutorial.blogspot.in/2015/06/r-tutorial-for-beginners.html");
document.add(table);
document.close();
}
}
This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here