Skip to main content
Skip table of contents

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 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(IMG));

        // Draws an image as the cell's background
        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.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.