java iText anchor

The Anchor is a subclass of Paragraph and represents a link, simply like a website link. It is represented by com.itextpdf.text.Anchor class.

Steps:

1. Create Document instance. It represents the current document to which we are adding content.
2. Create OutputStream instance. It represents the generated pdf.
3. Create PDFWriter instance and pass Document and OutputStream instance to its constructor.
4. Open the Document by calling document.open().
5. Add the content to the document by calling document.add() method using Anchor object.
6. Close the document by calling document.close() method.

Example:

PDFAnchorExample.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import com.itextpdf.text.Anchor;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
 
/**
* This class is used to create a pdf file using iText jar.
* @author javawithease
*/

public class PDFAnchorExample {
public static void main(String args[]){
try {
//Create Document instance.
Document document = new Document();
 
//Create OutputStream instance.
OutputStream outputStream =
new FileOutputStream(new File("D:\\TestAnchorFile.pdf"));
 
//Create PDFWriter instance.
PdfWriter.getInstance(document, outputStream);
 
//Open the document.
document.open();
 
//Create Anchor object
Anchor anchor = new Anchor("http://tutorialspointexamples.com/");
anchor.setReference("http://tutorialspointexamples.com/");
 
//Add content to the document using Anchor object.
document.add(anchor);
 
//Close document and outputStream.
document.close();
outputStream.close();
 
System.out.println("Pdf created successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Output:

Pdf created successfully.

No comments: