Using iTextSharp
, I want to put a stamp on a PDF and make it transparent. The stamp has colored text on it (various colors) that becomes difficult to read when the entire image is transparent, so I don't want to make the colored text transparent - only the white background in the stamp's rectangle.
Based on this answer, I tried the following code:
public void addImage(PdfDictionary oldAnnot, string imagePath,
int pageNumber,iTextSharp.text.Rectangle someRectangle) {
Stream inputImageStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read, FileShare.Read);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
PdfAnnotation pdfStamp = PdfAnnotation.CreateStamp(pdfStamper.Writer, someRectangle, null, Guid.NewGuid().ToString());
image.SetAbsolutePosition(0, 0);
PdfAppearance app = pdfStamper.GetOverContent(pageNumber).CreateAppearance(image.Width, image.Height);
app.SaveState();
PdfGState state = new PdfGState();
state.FillOpacity = 0.1f;
app.SetGState(state);
app.AddImage(image);
app.RestoreState();
pdfStamp.SetAppearance(PdfName.N, app);
pdfStamp.SetPage();
pdfStamper.AddAnnotation(pdfStamp, pageNumber);
}
However, this makes the colored parts of the image translucent. How can I make only the blank background of the image transparent and leave the colored parts opaque?
Thanks.
You essentially are asking for the Colour Key Masking PDF feature. Unfortunately
When colour key masking is specified, the use of a DCTDecode or lossy JPXDecode filter for the stream can produce unexpected results.
(section 8.9.6.4 – Colour Key Masking – ISO 32000-1)
As you have a JPEG and JPEGs usually are embedded in PDFs using the DCTDecode filter, Colour Key Masking might not work as desired.
Instead of working with transparency you might want to try using a different blend mode, e.g. Darken or Multiply.
Multiply B(cb, cs) = cb * cs
NOTE 1 Multiplies the backdrop and source colour values.
NOTE 2 The result colour is always at least as dark as either of the two constituent colours. Multiplying any colour with black produces black; multiplying with white leaves the original colour unchanged. Painting successive overlapping objects with a colour other than black or white produces progressively darker colours.
Darken B(cb, cs) = min(cb, cs)
NOTE 6 Selects the darker of the backdrop and source colours.
NOTE 7 The backdrop is replaced with the source where the source is darker; otherwise, it is left unchanged.
(Table 136 – Standard separable blend modes – ISO 32000-1)
To select a blend mode, you can use a PdfGState
like you already do but instead of setting the opacity
state.FillOpacity = 0.1f;
you set the blend mode
state.BlendMode = PdfGState.BM_MULTIPLY;
or
state.BlendMode = PdfGState.BM_DARKEN;