Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add image watermark over another image in pdf c#

Tags:

c#

itextsharp

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 : This is the problematic image

like image 714
Ahmed Masud Avatar asked Dec 12 '22 16:12

Ahmed Masud


1 Answers

I just got it working by replacing

PdfContentByte pdfData = pdfStamper.GetUnderContent(pageIndex);

with

PdfContentByte pdfData = pdfStamper.GetOverContent(pageIndex);
like image 107
Ahmed Masud Avatar answered Dec 14 '22 05:12

Ahmed Masud