How to underline text example in PDF using java iText library

In this tutorial you will learn to create the underline text in PDF document using iText java library.

Please note we are using the iText version 5 for this example.

You can create the text using Chunk element and can add the underline in same chunk by calling the method setUnderline().

Below is the example of code which shows you how to add underlined text in PDF document using iText java library.

import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfWriter;
public class PDFUnderlineTextExample {
    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_Underline_Text_Example.pdf");
        // Get a PdfWriter instance to write in PDF document.
        PdfWriter.getInstance(document, out);
        // Open the PDF document;
        // Create a Chunk element with some text.
        Chunk underline = new Chunk("This is underlined text.");
        // Set the underline of text
        underline.setUnderline(0.1f, -2f);
        // Add the chunk element in document
        // Close the document after use.

The generated PDF document looks like below screen.