0

I have a table where in the first row there are only images and in the second row there are only descriptions of the images. I handle this by creating a table with the size (columns) of the amount of images and then filling the cells with tables with size 1 (2 rows = 1st row the image, 2nd row the description). After setting cell alignment of the 1st row to center, the second row will not apply the align and the description stays on the left ... is this a bug?

    Integer size = filepathArray.length;
    PdfPTable pdfPTable = new PdfPTable(size); 
    for (int i = 0; i < size; i++) {
        PdfPTable inner = new PdfPTable(1);
        try {
            PdfPCell image = new PdfPCell();
            PdfPCell description = new PdfPCell();
            PdfPCell cell = new PdfPCell();
            image.setImage(Image.getInstance(getImageAsByteArray(filepathArray[i])));
            image.setFixedHeight(32);
            image.setBorder(Rectangle.NO_BORDER);
            image.setHorizontalAlignment(Element.ALIGN_CENTER);
            inner.addCell(image);
            description.addElement(new Chunk(filepathArray[i], FontFactory.getFont("Arial", 8)));
            description.setBorder(Rectangle.NO_BORDER);
            description.setHorizontalAlignment(Element.ALIGN_CENTER);
            inner.addCell(description);
            cell = new PdfPCell();
            cell.addElement(inner); // needed to actually remove the border from the cell which contains the inner table because tables have no setter for the border
            cell.setBorder(Rectangle.NO_BORDER);
            pdfPTable.addCell(cell);
        } catch (Exception e) {
        }
    }
    pdfPTable.setHorizontalAlignment(Element.ALIGN_LEFT);

Result: the image is centered, the text is not, no way, I've tried everything! Also addElement() removes all previously set alignments (table and cell elements, is this a bug?) so I have to set the alignment AFTER I added the content to the cell or table.

Pali
  • 1,337
  • 1
  • 14
  • 40

1 Answers1

2

This is wrong:

PdfPCell description = new PdfPCell();
description.addElement(new Chunk(filepathArray[i], FontFactory.getFont("Arial", 8)));
description.setHorizontalAlignment(Element.ALIGN_CENTER);

It is wrong because you are mixing text mode:

PdfPCell description = new PdfPCell(new Phrase(filepathArray[i], FontFactory.getFont("Arial", 8)));
description.setHorizontalAlignment(Element.ALIGN_CENTER);

With composite mode:

PdfPCell description = new PdfPCell();
Paragraph p = new Paragraph(filepathArray[i], FontFactory.getFont("Arial", 8));
p.setAlignment(Element.ALIGN_CENTER);
description.addElement(p);

Seems like you have tried everything but using the approaches that are explained in the documentation ;-)

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
  • what should I say ... I am lazy at reading (especially documentations) ;) shame on me! But thank you so much, it's working now! YEAH! – Pali Jun 24 '15 at 13:36