2013-03-25 134 views
4

全部,在pdf c中将图像水印添加到另一图像中#

我试图在使用itextsharp的pdf中添加图像水印。如预期的那样,水印出现在所有页面上,但已经有图像。我希望我的水印图像位于PDF上现有图像的顶部。 我使用下面的代码添加图像

 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(); 
     } 

我附上当前的代码也输出: This is the problematic image

回答

12

我刚刚才用

更换

PdfContentByte pdfData = pdfStamper.GetUnderContent(pageIndex); 

工作

PdfContentByte pdfData = pdfStamper.GetOverContent(pageIndex); 
+0

为我节省了很多时间!谢谢。 – 2014-04-14 00:09:30

0

替换

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

随着

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

,并删除

jpeg.SetAbsolutePosition(50, 50); 

得到水印中心

+0

该op并没有要求帮助中心的形象,但为了帮助使其可见。接受的答案明确地解决了他的代码中的问题。 – mkl 2017-02-04 00:26:42