Image transparency in PDF using iTextSharp

匆匆过客 提交于 2020-01-15 05:23:58

问题


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.



来源:https://stackoverflow.com/questions/47600327/image-transparency-in-pdf-using-itextsharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!