The width of a table column defined relatively between each column. On the following example we define an array floats that stores the column widths. We define the second column twice as big as the first column and the third column is three times bigger than the first column.
To set the width we call the table
‘s setWidths()
method. This method can accept an array of floats or an array of integers. Here is an example code:
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 TableColumnWidthDemo {
public static void main(String[] args) {
Document doc = new Document();
try {
PdfWriter.getInstance(doc, new FileOutputStream("TableColumnWidth.pdf"));
doc.open();
PdfPTable table = new PdfPTable(4);
table.addCell(new PdfPCell(new Phrase("Cell 1")));
table.addCell(new PdfPCell(new Phrase("Cell 2")));
table.addCell(new PdfPCell(new Phrase("Cell 3")));
table.addCell(new PdfPCell(new Phrase("Cell 4")));
// Defiles the relative width of the columns
float[] columnWidths = new float[]{10f, 20f, 30f, 10f};
table.setWidths(columnWidths);
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>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Hi, How can I wrap the cell contents of a particular cell?
Define separate cells and set them to
cell.setNoWrap(false)
.Above code is working. But it is not working in while loop. And, it is says wrong no.of columns