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", "https://self-learning-java-tutorial.blogspot.com"); addHyperLink(table, "MongoDB Tutorial", "https://self-learning-java-tutorial.blogspot.com/2016/05/mongodb-home.html"); addHyperLink(table, "R Tutorial for beginners", "https://self-learning-java-tutorial.blogspot.com/2015/06/r-tutorial-for-beginners.html"); document.add(table); document.close(); } }
No comments:
Post a Comment