Home iText PDF tutorials

External link example in PDF using java iText library

In this tutorial you will how to add anchor text external link in PDF document. The iText Anchor class represents a link which can be reference to external URL.

 An Anchor class can be a reference or a destination of a reference. The Anchor is a special kind of Phrase.

The example below show the use of Anchor class to create external link.

package com.java.connect.itext;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;

import com.lowagie.text.Anchor;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfWriter;

public class PDFExternalLinkExample {
	public static void main(String[] args) throws FileNotFoundException, DocumentException {

		// Create new PDF document
		Document document = new Document();
		// Create an output stream of PDF file.
		OutputStream out = new FileOutputStream("PDF_External_Link_Example.pdf");
		// Get a PdfWriter instance to write in PDF document.
		PdfWriter.getInstance(document, out);
		// Open the PDF document
		// Create the Paragraph element
		Paragraph paragraph = new Paragraph();
		// Add a new Phrase to add some sentance.
		paragraph.add(new Phrase("You can find some useful IText tutorial at "));
		// Create the Anchor and some link.
		Anchor anchor = new Anchor("http://www.java-connect.com/itext/index.html");
		// set the refrence on the text.
		// Add the Anchor element to paragraph.
		// Add the paragraph to PDF document
		// Close the PDF document after use.


The output of generated PDF document looks like below screen.