Drawing shapes with a translucent fill in iTextSharp 4.1.6.0

10,266

One of the rules of converting Java libraries to C# libraries is that all of the getXYZ and setXYZ methods should be converted to simple C# properties. So gstate.setFillOpacity(0.3); will be come gstate.FillOpacity = 0.3f;

    using (Document doc = new Document())
    {
        PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(@"mod.pdf", FileMode.Create));
        doc.Open();
        PdfContentByte over = writer.DirectContent;

        over.SaveState();

        over.Rectangle(10, 10, 50, 50);
        over.SetColorFill(BaseColor.BLUE);
        over.Fill();


        PdfGState gs1 = new PdfGState(); 
        gs1.FillOpacity = 0.5f;
        over.SetGState(gs1);

        over.Rectangle(0, 0, 60, 60);
        over.SetColorFill(new BaseColor(255, 0, 0, 150));
        over.Fill();

        over.RestoreState();

        doc.Close();
    }
Share:
10,266
Ben
Author by

Ben

Updated on June 04, 2022

Comments

  • Ben
    Ben almost 2 years

    I am using a deprecated version of iTextSharp (4.1.6.0) to produce PDFs form my MVC3 application, and really need to be able to lay translucent shapes over the top of other shapes and images, the goal being to fade the colours of the image underneath it, or grey it out. I would have thought this would be as simple as setting the alpha channel when choosing a colour for the shapes fill, so i tried this:

    Document doc = new Document();
    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(@"C:/Filepath/doc.pdf", FileMode.Create))
    doc.Open();
    PdfContentByte over = writer.DirectContent;
    
    // draw shape to be faded out
    over.Rectangle(10, 10, 50, 50);
    over.SetColorFill(Color.BLUE);
    over.Fill();
    
    // draw shape over the top to do the fading (red so i can easily see where it is)
    over.Rectangle(0, 0, 60, 60);
    over.SetColorFill(new Color(255,0,0,150)); // rgba
    over.Fill();
    
    doc.Close();
    

    I would expect this to draw two rectangles near the bottom left of the page, a small blue one overlaid with a larger red, translucent one, but the red one is not translucent!

    So i did some googling and found this page, which is actually about iText not iTextSharp, where they suggest using PdfGstate to set the fill opacity like this:

    PdfGState gstate = new PdfGState();
    gstate.setFillOpacity(0.3);
    

    but when i try that the gstate object has no method that is anything like .setFillOpacity()! If anyone can point me in the right direction I would be most grateful.