We can set the width of a table using the setWidthPercentage()
method of the com.itextpdf.text.pdf.PdfPTable
class. This method accept a float value as a parameter. This method sets the width in a percentage of the width a table will occupy in the page. The default table’s width is 80%.
Let’s see an example on the following 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 TableWidthDemo {
public static void main(String[] args) {
Document doc = new Document();
try {
PdfWriter.getInstance(doc, new FileOutputStream("TableWidthDemo.pdf"));
doc.open();
// Creates a table with 5 columns
PdfPTable table = new PdfPTable(5);
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")));
table.addCell(new PdfPCell(new Phrase("Cell 5")));
// Sets the width percentage that the table will occupy
// in the page.
table.setWidthPercentage(50);
doc.add(table);
} catch (DocumentException | FileNotFoundException e) {
e.printStackTrace();
} finally {
doc.close();
}
}
}
Maven Dependencies
<!-- https://search.maven.org/remotecontent?filepath=com/itextpdf/itextpdf/5.5.13.3/itextpdf-5.5.13.3.jar -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
</dependency>
Latest posts by Wayan (see all)
- How do I build simple search page using ZK and Spring Boot? - March 8, 2023
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023
How to set width for all pages using iText?