How to create a table in which the cells have different widths?
How to create a table with Java that has three rows as follows:
- First row has one cell 100% entire table width
- Second row has first from the left cell width 50mm, and second 20mm and third 30mm which in total is 100% of table width
- Third row has first from the left cell width 30mm, and second 50mm and third 10mm which in total is 90% of table width
In short: what would the iText code look like if I wanted a table as shown here:
Question posted on StackOverflow on Dec 30, 2015 by mCs
So you want to use iText to create a table that looks like this:
Table with cells of different width
The PDF in the screen shot was created using the TableMeasurements example. The resulting PDF can also be downloaded for inspection: table_measurements.pdf
The first thing that jumps to the eye when looking at this screenshot is the fact that the table doesn't look "complete". But for iText7 it is not a problem:
In your case, we'd have something like this:
public void manipulatePdf(String dest) throws Exception {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
Table table = new Table(10);
table.setWidth(millimetersToPoints(100));
table.addCell(getCell(10));
table.addCell(getCell(5));
table.addCell(getCell(3));
table.addCell(getCell(2));
table.addCell(getCell(3));
table.addCell(getCell(5));
table.addCell(getCell(1));
doc.add(table);
doc.close();
}
To make the example more realistic, I created a table with an exact width of 100 mm. I add all the cells with the different widths (10 cm, 5 cm, 3 cm, 2 cm, 3 cm, 5 cm, 1 cm).
What does the getCell()
method look like, you might wonder. This is shown here:
private Cell getCell(int cm) {
Cell cell = new Cell(1, cm);
Paragraph p = new Paragraph(
String.format("%smm", 10 * cm)).setFontSize(8);
p.setTextAlignment(TextAlignment.CENTER);
cell.add(p);
return cell;
}
We create a Cell
and we set the colspan to reflect the width in cm.
Click How to create a table in which the cells have different widths? if you want to see how to answer this question in iText 5.