Tech and Media Labs
This site uses cookies to improve the user experience.




Java IText: Chunk

Jakob Jenkov
Last update: 2014-05-24

The com.itextpdf.text.Chunk class in IText represents the smallest possible "chunk" of text. A Chunk can contain as little as a single character, up to several sentences.

Here is a simple code example:

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;

public class DocumentExample {

    public static void main(String[] args) {

        Document document = new Document();

        try {
            PdfWriter.getInstance(document,
                    new FileOutputStream("Chunk.pdf"));

            document.open();
            document.add(new Chunk("This is sentence 1. "));
            document.add(new Chunk("This is sentence 2. "));
            document.add(new Chunk("This is sentence 3. "));
            document.add(new Chunk("This is sentence 4. "));
            document.add(new Chunk("This is sentence 5. "));
            document.add(new Chunk("This is sentence 6. "));
            document.close();

        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

Here is what the generated document looks like:

An IText Chunk example
An IText Chunk example

Notice how sentence 1 and sentence 6 are printed ontop of each other. The IText Chunk object does not add line breaks, paragraph spacing or any other kind of spacing. It just adds the raw text at the next available location, left to right. When it reaches the right edge of the document, it restarts from the left edge, at the same Y location (same height).

Jakob Jenkov




Copyright  Jenkov Aps
Close TOC