2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Create a table of 2x2 inside PDF using itext

I am quite new to generate PDF using itext. So I need some sample code to create a table  which containg 2 rows and 2 columns and generate the PDF. Please help.
userimage

Here you can find the snippet use full with your requirement.


Document document = new Document();
PdfWriter writer = null;
try {
    writer = PdfWriter.getInstance(document, new FileOutputStream("TableTestExample.pdf"));
    document.open();

    PdfContentByte canvas = writer.getDirectContent();
    canvas.beginText();

    System.out.println("==Start==");
    PdfPTable table = new PdfPTable(2);
    table.setTotalWidth(document.getPageSize().getWidth() - 24);
    table.setLockedWidth(true);

    PdfPCell cell1r1;
    cell1r1 = new PdfPCell(new Phrase("Cell 1 Row 1"));
    cell1r1.setColspan(1);
    cell1r1.setPadding(5);
    table.addCell(cell1r1);

    PdfPCell cell2r1;
    cell2r1 = new PdfPCell(new Phrase("Cell 2 Row 1"));
    cell2r1.setColspan(1);
    cell2r1.setPadding(5);
    table.addCell(cell2r1);

    PdfPCell cell1r2;
    cell1r2 = new PdfPCell(new Phrase("Cell 1 Row 2"));
    cell1r2.setColspan(1);
    cell1r2.setPadding(5);
    table.addCell(cell1r2);

    PdfPCell cell2r2;
    cell2r2 = new PdfPCell(new Phrase("Cell 2 Row 2"));
    cell2r2.setColspan(1);
    cell2r2.setPadding(5);
    table.addCell(cell2r2);

    table.writeSelectedRows(0, -1, 12, 680, canvas);
    System.out.println("==End==");
    canvas.endText();
    document.close();
    writer.close();
} catch (FileNotFoundException | DocumentException e) {
    e.printStackTrace();
}


Tested with itextpdf-5.1.0.jar

Answer is