Add image watermark over another image in pdf c#

时光毁灭记忆、已成空白 提交于 2019-12-06 04:59:11

问题


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 :


回答1:


I just got it working by replacing

PdfContentByte pdfData = pdfStamper.GetUnderContent(pageIndex);

with

PdfContentByte pdfData = pdfStamper.GetOverContent(pageIndex);



回答2:


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 remove

jpeg.SetAbsolutePosition(50, 50);

to get watermark centered



来源:https://stackoverflow.com/questions/15612044/add-image-watermark-over-another-image-in-pdf-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!