How do I set Paragraph line space in iText?

To set the line spacing of a paragraph in iText can be done by passing the line space / leading argument in the Paragraph constructor. In the example below we set the line space to 32. We can also set the space between paragraph by calling the setSpacingBefore() and setSpacingAfter() methods of this object.

package org.kodejava.example.itextpdf;

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

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

public class ParagraphLineSpaceDemo {
    public static void main(String[] args) {
        Document doc = new Document();

        try {
            FileOutputStream fos = new FileOutputStream("ParagraphLineSpace.pdf");
            PdfWriter.getInstance(doc, fos);
            doc.open();

            String content = "The quick brown fox jumps over the lazy dog";

            // Setting paragraph line spacing to 32
            Paragraph para1 = new Paragraph(32);

            // Setting the space before and after the paragraph
            para1.setSpacingBefore(50);
            para1.setSpacingAfter(50);
            for (int i = 0; i < 10; i++) {
                para1.add(new Chunk(content));
            }
            doc.add(para1);

            Paragraph para2 = new Paragraph();
            for (int i = 0; i < 10; i++) {
                para2.add(new Chunk(content));
            }
            doc.add(para2);

            doc.close();
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

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

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