Skip to main content
Skip table of contents

Why is content missing in my table?

I am adding image cells based on an imagelist that may not contain 6 or 12 or 18 images. The number of images can be 1 or 7 or anything.


Here's my scenario: I create a PdfPTable with 6 columns. However, when I add only 1 or 2 cells to the table, it's not rendering those cells. It only renders the cells if I add 6 or a multiple of 6 cells.

I know that makes total sense but in my case, I am adding image cells based on an imagelist that may not contain 6 or 12 or 18 images. The number of images can be 1 or 7 or anything. Below is my Q> snippet:


try {
    Document document = new Document(PageSize.A4.rotate());
    PdfWriter writer = PdfWriter.getInstance(document,
        new FileOutputStream(new File(sourcePath, AppText.FILE_NAME)));
    PdfPTable table = new PdfPTable(6);
    document.open();
    Paragraph paragraph = new Paragraph("Diary Report");
    paragraph.setSpacingAfter(50);
    paragraph.setSpacingBefore(50);
    document.add(paragraph);
    table.setHorizontalAlignment(Element.ALIGN_LEFT);
    for (String imageFile : imageFiles) {
        Image image = Image.getInstance(new File(imageFile).getAbsolutePath());
        PdfPCell cell = new PdfPCell(image, true);
        cell.setPadding(10);
        table.addCell(cell);
    }
    document.add(table);
    document.close();
    return "successful";
} catch (DocumentException | IOException e) {
    e.printStackTrace();
}
Any help would be so great.

Posted on StackOverflow on Nov 20, 2015 by prashantwosti

The way of creating tables in iText 7 differs from the previous version. You should replace PdfPTable and PdfPCell instances with Table and Cell respectively. Look at the IncompleteTable example. With a few changes your code will look like this:

public void createPdf(String imgSrc, String dest) throws IOException {
    PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
    Document doc = new Document(pdfDoc);
    Image img = new Image(ImageDataFactory.create(imgSrc)).setAutoScale(true);
    Table table = new Table(6, true);
    for (int i = 1; i 

As you see, we create a table with 6 columns, setting the second parameter in the constructor as true. It means that the table, being added to the document, will not be complete. In the first loop we add a header with a Paragraph instances. Then add the table to the document. In the second loop we add new cells with images, but in such a way, that the last (third) row will have only 2 cells. Executing complete() method we tell iText to render all cells.

The result looks like this:

Screenshot

Screenshot

Click this link if you want to see how to answer this question in iText 5.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.