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
		document.open();
		// 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.
		anchor.setReference("http://www.java-connect.com/itext/index.html");
		// Add the Anchor element to paragraph.
		paragraph.add(anchor);
		// Add the paragraph to PDF document
		document.add(paragraph);
		// Close the PDF document after use.
		document.close();
	}
}

 

The output of generated PDF document looks like below screen.