How do I set line space in Paragraph?

To set the line spacing in a paragraph 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 ParagraphSpaceDemo {
    public static void main(String[] args) {
        Document document = new Document();

        try {
            String name = "ParagraphSetting.pdf";
            FileOutputStream fos = new FileOutputStream(name);
            PdfWriter.getInstance(document, fos);
            document.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));
            }
            document.add(para1);

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

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

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.9</version>
</dependency>
Wayan Saryada

Wayan Saryada

A programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, JPA, etc. If you need help on Java programming you can hire me on Fiverr.
Wayan Saryada

Leave a Reply