You can set the cell’s padding using the com.itextpdf.text.pdf.PdfPCell
‘s setPadding()
method. To set the padding individually you can use the setPaddingTop()
, setPaddingRight()
, setPaddingBottom()
, and setPaddingLeft()
methods to set the top, right, bottom and left padding respectively.
package org.kodejava.itextpdf;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class TableCellPadding {
public static void main(String[] args) {
Document doc = new Document();
try {
PdfWriter.getInstance(doc, new FileOutputStream("TableCellPadding.pdf"));
doc.open();
int numColumns = 3;
PdfPTable table = new PdfPTable(numColumns);
PdfPCell[] cells = new PdfPCell[numColumns];
for (int i = 0; i < numColumns; i++) {
cells[i] = new PdfPCell(new Phrase("Cell " + i + 1));
// Set cell's padding equally for all side of the
// cell.
cells[i].setPadding(10);
table.addCell(cells[i]);
}
table.completeRow();
cells = new PdfPCell[numColumns];
for (int i = 0; i < numColumns; i++) {
cells[i] = new PdfPCell(new Phrase("Cell " + i + 1));
// Set cell's padding individually for top, right,
// bottom and left padding.
cells[i].setPaddingTop(20);
cells[i].setPaddingRight(30);
cells[i].setPaddingBottom(20);
cells[i].setPaddingLeft(30);
table.addCell(cells[i]);
}
table.completeRow();
doc.add(table);
} catch (DocumentException | FileNotFoundException e) {
e.printStackTrace();
} finally {
doc.close();
}
}
}
Maven Dependencies
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
</dependency>