Skip to main content
Skip table of contents

How to change a background Image into a watermark by altering the opacity?

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);

Any idea?

Posted on StackOverflow on Dec 2, 2014 by dandy

Please take a look at the BackgroundTransparent example. It is a variation of 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 PdfExtGState defining the opacity:

PdfCanvas canvas = new PdfCanvas(pdfDoc.addNewPage());
ImageData image = ImageDataFactory.create(imgSrc);
PdfExtGState state = new PdfExtGState();
canvas.addImage(image, 0, 0, pageSize.getWidth(), false);

You can compare the results of the examples mentioned above to see the difference.

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

Click How to change a background Image into a watermark by altering the opacity? if you want to see how to answer this question in iText 5.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.