Question

I created the pdf using iText. In that, how to set the background image to the particular PdfCell and place the text in that same cell..

I set the background image to that cell by:

    cell.addElement(image_green_left);

In case of both text and image, it show only image and text was hidden.

    cell.addElement(image_green_left);
    cell.addElement(new Paragraph("Test 3"));
    table.addCell(cell);

How to show both text and image?

Was it helpful?

Solution

Create your own implementation of a PdfPCellEvent, for instance:

class ImageBackground implements PdfPCellEvent {
    protected Image image;
    public ImageBackground(Image image) {
        this.image = image;
    }
    public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
        PdfContentByte cb = canvases[PdfPTable.BACKGROUNDCANVAS];
        Image.scaleToFit(position.getWidth() , position.getHeight());
        Image.setAbsolutePosition(position.getBottom(), position.getLeft());
        cb.addImage(image);
    }
}

Now when cell is the PdfPCell with the text and bgImage the path to your image, do this:

Image image = Image.getInstance(bgImage);
cell.setCellEvent(new ImageBackground(image));

Now, you'll have an image that acts as the background of the cell.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top