Add watermark image over another image in pdf C #

Everything,

I am trying to add image watermark to pdf using itextsharp. A watermark appears on all pages as expected, but with those that already have an image. I want my watermarked image to appear on top of an existing pdf image. I use the following code to add an image

using (Stream output = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) { using (PdfStamper pdfStamper = new PdfStamper(pdfReader, output)) { for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++) { pdfStamper.FormFlattening = false; iTextSharp.text.Rectangle pageRectangle = pdfReader.GetPageSizeWithRotation(pageIndex); PdfContentByte pdfData = pdfStamper.GetUnderContent(pageIndex); pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 10); PdfGState graphicsState = new PdfGState(); graphicsState.FillOpacity = 0.4F; pdfData.SetGState(graphicsState); pdfData.BeginText(); iTextSharp.text.Image jpeg = iTextSharp.text.Image.GetInstance(wtrmrkimg, BaseColor.GREEN); float width = pageRectangle.Width; float height = pageRectangle.Height; jpeg.ScaleToFit(width, height); jpeg.SetAbsolutePosition(width / 2 - jpeg.Width / 2, height / 2 - jpeg.Height / 2); jpeg.SetAbsolutePosition(50, 50); jpeg.Rotation = 45; pdfData.AddImage(jpeg); pdfData.EndText(); } pdfStamper.Close(); } output.Close(); output.Dispose(); } 

I also add the output of the current code: This is the problematic image

+4
source share
2 answers

I just earned by replacing

 PdfContentByte pdfData = pdfStamper.GetUnderContent(pageIndex); 

with

 PdfContentByte pdfData = pdfStamper.GetOverContent(pageIndex); 
+12
source

Replace

 jpeg.SetAbsolutePosition(width / 2 - jpeg.Width / 2, height / 2 - jpeg.Height / 2); 

WITH

 jpeg.SetAbsolutePosition(width / 2 - jpeg.ScaledWidth / 2, height / 2 - jpeg.ScaledHeight / 2); 

and delete

 jpeg.SetAbsolutePosition(50, 50); 

for centering watermarks

0
source

All Articles