Thursday, June 21, 2012

Image + Text in iText PdfPCell

Recently, while working on the project involving creating PDFs with iText library, I needed to create PDF with cells that have image and text inside of them. After some searching and playing around, the following piece of code solved the problem:
Paragraph paragraph = new Paragraph();
if (image != null) {
      image.scalePercent(90f);
      paragraph.add(new Chunk(image, -1f, 1f));
}
font.setColor(WebColors.getRGBColor(fontColor));
paragraph.add(new Phrase(text, font));
PdfPCell cell = new PdfPCell(paragraph);
cell.setBorder(Rectangle.LEFT);
cell.setBorder(Rectangle.RIGHT);
cell.setBorderColor(WebColors.getRGBColor(BORDER_COLOR));
cell.setBackgroundColor(WebColors.getRGBColor(backgroundColor));
table.addCell(cell);
One thing to notice, initially, I had an issue with image stretching to the height of the cell. The fix for that problem is in RED in the code above.

No comments:

Post a Comment