In this example, we'll create the following table using iText 5:
We need the PdfPTable
and PdfPCell
class to achieve this:
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
PdfPTable table = new PdfPTable(3);
PdfPCell cell = new PdfPCell(new Phrase("Cell with colspan 3"));
cell.setColspan(3);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("Cell with rowspan 2"));
cell.setRowspan(2);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cell);
table.addCell("Cell 1.1");
cell = new PdfPCell();
cell.addElement(new Phrase("Cell 1.2"));
table.addCell(cell);
cell = new PdfPCell(new Phrase("Cell 2.1"));
cell.setPadding(5);
cell.setUseAscender(true);
cell.setUseDescender(true);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell();
cell.setPadding(5);
cell.setUseAscender(true);
cell.setUseDescender(true);
Paragraph p = new Paragraph("Cell 2.2");
p.setAlignment(Element.ALIGN_CENTER);
cell.addElement(p);
table.addCell(cell);
document.add(table);
document.close();
}
Source: developers.itextpdf.com