I am using iText to generate Pdf Reports for data in a database...
The header of the pages of the pdfs is an image with some text on the image added dynamically, say for example date generated..
Anyone knows if we can set background images to Tables of type PdfPTable in itext..
Thanks
I know its very late but might help someone. Here is the way to do it.
Create a class BGClass, implement PdfPCellEvent and enter following method.
@Override
public void cellLayout(PdfPCell arg0, Rectangle arg1, PdfContentByte[] arg2) {
try {
PdfContentByte pdfContentByte = arg2[PdfPTable.BACKGROUNDCANVAS];
Image bgImage = Image.getInstance("URL_TO_YOUR_IMAGE");
pdfContentByte.addImage(bgImage, arg1.getWidth(), 0, 0, arg1
.getHeight(), arg1.getLeft(), arg1.getBottom());
} catch (BadElementException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
In your main class, where you are creating PDF, pdfpCell.setCellEvent(new BGClass()); where pdfpCell is the cell for which you want background image.
Prabhat's technique has a flaw or two.
- A copy of the image is added to the PDF for each cell. Store the returned Image between cellLayout calls so you'll have just one copy. If you have a 10x10 table and a 10kb image, you're taking up 1mb instead of 10kb in the PDF. Ouch. And it's actually a little worse than that with the extra overhead of all those extra objects (not a lot worse, but measurable).
- It must tile the image, one per cell.
You're better off going with a PdfPTableEvent
. Note that if your table spans multiple pages, your event handler will be called once for each table. The heights
and widths
parameters are a bit funky. The first value in each is the absolute start position. The remaining values really are heights and widths. Handy, but the variable names are a tad misleading.
And keep in mind that each instance of an image means another copy of that image in your PDF. Save 'em and reuse 'em whenever you can.