2013-03-25 61 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