How to set background image in PdfPCell in iText?

I am currently using iText to generate PDF reports. I want to set a medium size image as a background in PdfPCell instead of using background color. Is this possible? Posted on StackOverflow on

I am currently using iText to generate PDF reports. I want to set a medium size image as a background in PdfPCell instead of using background color. Is this possible?

Posted on StackOverflow on Jun 11, 2014 by user1283475

You need to create your own implementation of the PdfPCellEvent interface, for instance:

class ImageBackgroundEvent implements PdfPCellEvent {

    protected Image image;

    public ImageBackgroundEvent(Image image) {
        this.image = image;
    }

    public void cellLayout(PdfPCell cell, Rectangle position,
            PdfContentByte[] canvases) {
        try {
            PdfContentByte cb = canvases[PdfPTable.BACKGROUNDCANVAS];
            image.scaleAbsolute(position);
            image.setAbsolutePosition(position.getLeft(), position.getBottom());
            cb.addImage(image);
        } catch (DocumentException e) {
            throw new ExceptionConverter(e);
        }
    }

Then you need to create an instance of this event and declare it to the cell that needs this background:

Image image = Image.getInstance(IMG1);
cell.setCellEvent(new ImageBackgroundEvent(image));

Take a look at the ImageBackground example for the full code.



Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now