How do I create an underlined or strike through chunk in iText?

You can use the Chunk‘s setUnderline(float thickness, float yPosition) method to add underline or strike through to a chunk. A negative value to the yPosition create an underline while a positive value will produce a strike through.

package org.kodejava.example.itextpdf;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;

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

public class UnderlineStrikeThroughDemo {
    public static void main(String[] args) {
        Document doc = new Document();
        try {
            PdfWriter.getInstance(doc, new FileOutputStream("UnderStrike.pdf"));
            doc.open();

            // Creates a chunk with an underline with 0.1 thickness
            Chunk underline = new Chunk("The quick brown fox ");
            underline.setUnderline(0.1f, -1f);
            doc.add(underline);

            // Creates a strike through chunk with 1 thickness
            Chunk strike = new Chunk("jumps over the lazy dog.");
            strike.setUnderline(1f, 3f);
            doc.add(strike);
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            doc.close();
        }
    }
}

Maven Dependencies

<!-- http://repo1.maven.org/maven2/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.10</version>
</dependency>

Wayan Saryada

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply