Image transparency in PDF using iTextSharp

2019-07-22 07:44发布

问题:

I have an incoming jpg file, that I can set a colour to transparent. When I add the image to another image, this works perfectly.

I am trying to add the same image to a PDF using iTextSharp, but I cannot get the transparency to work.

I have tried two ways, but neither is working. The first way was to open the image in a Bitmap, set transparency, then use that Bitmap object in the PDF. The second way (shown here) was saving the Bitmap to disk and opening the file into the iTextSharp image.

                    using (Bitmap b = new Bitmap(Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("~/IncomingData/" + ImageFileName))))
                    {
                        b.MakeTransparent(Color.White);
                        b.Save(System.Web.HttpContext.Current.Server.MapPath("~/IncomingData/" + GuidFileName), System.Drawing.Imaging.ImageFormat.Png);
                        ImageFileName = GuidFileName;

                        iTextSharp.text.Image savedImage = iTextSharp.text.Image.GetInstance(Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("~/IncomingData/" + GuidFileName)), iTextSharp.text.Color.WHITE);

                        savedImage.SetAbsolutePosition(Convert.ToSingle(x + 1.0), Convert.ToSingle(imageY + 12) - Convert.ToSingle(h));
                        savedImage.ScaleToFit(Convert.ToSingle(w), Convert.ToSingle(h));
                        contentByte.AddImage(savedImage, true);
                    }

I have seen that there is a Transparency option...

savedImage.Transparency = ???

but I don't know what to put in the values. I can't find anything on my searches.

回答1:

Found the answer, eventually.

I saw this... and originally I was looking for .Transparency to find the transparency settings. I didn't see it. c# .NET CORE adding image with transparency to existing PDF using ITextSharp

My code is now...

                    using (Bitmap b = new Bitmap(Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("~/IncomingData/" + ImageFileName))))
                    {
                        b.MakeTransparent(Color.White);

                        iTextSharp.text.Image savedImage = iTextSharp.text.Image.GetInstance(b, System.Drawing.Imaging.ImageFormat.Png);

                        savedImage.SetAbsolutePosition(Convert.ToSingle(x + 1.0), Convert.ToSingle(imageY + 12) - Convert.ToSingle(h));
                        savedImage.ScaleToFit(Convert.ToSingle(w), Convert.ToSingle(h));

                        contentByte.AddImage(savedImage);
                    }

Note that the contentByte.AddImage has the boolean removed.