Search code examples
c#pdfitextcells

Image in bottom right corner of cell in iTextPdf


I'm struggling to find a way to place an image into bottom right corner of a cell in a table in iTextPdf.

I want to have image here: enter image description here

I was playing with IPdfPCellEvent, but no luck so far.

Right now there's a bunch of newlines at the end, so the text wrapping/overflow isn't an issue.


Solution

  • You can use a IPdfPCellEvent implementation like this one:

    public class ImageDecorator : IPdfPCellEvent
    {
        Image image;
    
        public ImageDecorator(Stream inputImageStream)
        {
            image = Image.GetInstance(inputImageStream);
            image.ScaleToFit(100, 100);
        }
    
        public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
        {
            PdfContentByte canvas = canvases[PdfPTable.BACKGROUNDCANVAS];
            canvas.AddImage(image, image.ScaledWidth, 0, 0, image.ScaledHeight, position.Right - image.ScaledWidth, position.Bottom);
        }
    }
    

    Using it like this

    using (Stream inputImageStream = new FileStream(imageURL, FileMode.Open, FileAccess.Read))
    using (FileStream fs = new FileStream(dest, FileMode.Create))
    {
        ImageDecorator imageDecorator = new ImageDecorator(inputImageStream);
    
        Document doc = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.GetInstance(doc, fs);
        doc.Open();
    
        string loremIpsum = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.";
        PdfPTable table = new PdfPTable(2);
    
        PdfPCell cell = new PdfPCell();
        cell.CellEvent = imageDecorator;
        cell.AddElement(new Paragraph(loremIpsum));
        table.AddCell(cell);
    
        cell = new PdfPCell();
        cell.CellEvent = imageDecorator;
        cell.AddElement(new Paragraph(loremIpsum));
        table.AddCell(cell);
    
        doc.Add(table);
    
        doc.Close();
    }
    

    I get

    screenshot