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

There is no PdfPCell class in iText 7. You should use Cell instead. To set your own custom background you need to extend CellRenderer and override draw() method like this:

private class ImageBackgroundCellRenderer extends CellRenderer {
    protected Image img;

    public ImageBackgroundCellRenderer(Cell modelElement, Image img) {
        super(modelElement);
        this.img = img;
    }

    @Override
    public void draw(DrawContext drawContext) {
        img.scaleToFit(getOccupiedAreaBBox().getWidth(), getOccupiedAreaBBox().getHeight());
        drawContext.getCanvas().addXObject(img.getXObject(), getOccupiedAreaBBox());
        super.draw(drawContext);
    }
}

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

Image img = new Image(ImageDataFactory.create(imgSrc));
cell.setNextRenderer(new ImageBackgroundCellRenderer(cell, img));

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

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


Share this article

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