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.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
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
</dependency>
Latest posts by Wayan (see all)
- How do I create a string of repeated characters? - September 1, 2023
- How do I convert datetime string with optional part to a date object? - August 28, 2023
- How do I split large excel file into multiple smaller files? - April 15, 2023