Search code examples
c#itextitext7

How to fill a shape with bitmap or mask a bitmap with shape in iText 7?


I want to fill a shape with a bitmap, in other words, mask a bitmap with a shape. I can't find a direct example. I am using iText 7 and C#.


Solution

  • You can fill a shape with a bitmap by making that shape a clip path and adding the bitmap, e.g. like this:

    using (PdfWriter writer = new PdfWriter(...))
    using (PdfDocument pdfDoc = new PdfDocument(writer))
    {
        ImageData data = ImageDataFactory.Create(...);
    
        PdfCanvas pdfCanvas = new PdfCanvas(pdfDoc.AddNewPage());
        pdfCanvas.SaveState()
                 .MoveTo(100, 100)
                 .LineTo(300, 200)
                 .LineTo(400, 400)
                 .LineTo(200, 300)
                 .ClosePath()
                 .EoClip()
                 .EndPath();
        pdfCanvas.AddImageAt(data, 100, 100, false);
        pdfCanvas.RestoreState();
    }
    

    (AddImageWithMask test testAddImageInShape)

    The result looks like this:

    enter image description here