How to set background image in PdfPCell in iText?

2019-08-02 07:24发布

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?

1条回答
乱世女痞
2楼-- · 2019-08-02 07:56

You can find an example on how to do this with iText 5.5.1 here. 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));

This code was tested with the most recent version of iText and the result looks like this. You're using a version of iText with my name (Lowagie) in the package names (com.lowagie). This means that this sample may or may not work. We don't know and we won't test as the version you're using has been declared EOL years ago. It is no longer supported.

查看更多
登录 后发表回答