All,
I am trying to add image watermark in pdf using itextsharp. Watermark is appearing on all the pages as expected but with ones that already have image. I want my watermarking image to come on top of the existing image on the pdf. I am using following code to add 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 am attaching output of the current code also :
I just got it working by replacing
PdfContentByte pdfData = pdfStamper.GetUnderContent(pageIndex);
with
PdfContentByte pdfData = pdfStamper.GetOverContent(pageIndex);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With