Change Background Image in Itext to watermark or alter opacity c# ASP.net

核能气质少年 提交于 2019-12-02 08:44:28

问题


I want to make my background image in iText transparent

here is my code for the image:

    string root = Server.MapPath("~");
    string parent = Path.GetDirectoryName(root);
    string grandParent = Path.GetDirectoryName(parent);
    string imageFilePath = parent + "/Images/logo.png";
    iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);
    jpg.ScaleToFit(1700, 800);
    jpg.Alignment = iTextSharp.text.Image.UNDERLYING;
    jpg.SetAbsolutePosition(100, 250);
    jpg.ScaleAbsoluteHeight(500);
    jpg.ScaleAbsoluteWidth(500);

Any idea?


回答1:


Please take a look at the BackgroundTransparant example. It is a variation on the BackgroundImage example.

In your code, you're adding the Image to the Document instance. That's OK, but if you want to make such an image transparent, you need to introduce a soft mask. That's not difficult, but there's an easier way to make your background transparent: add the image to the direct content, and introduce a PdfGState defining the opacity:

PdfContentByte canvas = writer.getDirectContentUnder();
Image image = Image.getInstance(IMAGE);
image.SetAbsolutePosition(0, 0);
canvas.SaveState();
PdfGState state = new PdfGState();
state.setFillOpacity(0.6f);
canvas.setGState(state);
canvas.addImage(image);
canvas.restoreState();

Compare background_image.pdf with background_transparent.pdf to see the difference.

My example is written in Java, but it's very easy to port this to C#:

PdfContentByte canvas = writer.DirectContentUnder;
Image image = Image.GetInstance(IMAGE);
image.SetAbsolutePosition(0, 0);
canvas.SaveState();
PdfGState state = new PdfGState();
state.FillOpacity = 0.6f;
canvas.SetGState(state);
canvas.AddImage(image);
canvas.RestoreState();


来源:https://stackoverflow.com/questions/27241731/change-background-image-in-itext-to-watermark-or-alter-opacity-c-sharp-asp-net

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