# VBForums CodeBank > CodeBank - Visual Basic .NET >  [VB.Net] Add watermark to existing Pdf file using iTextSharp

## stanav

Hello all again,
Recently, a vbforum member posted a question in VB.Net forum on how to add watermark to Pdf pages. Although I've never had to do it, but I know for sure that iTextSharp is capable of this. So I spent some spare time writing some code to do it using the free iTextSharp library, and here it is, the 2 subroutines for adding an image and text as the watermark on each page of a pdf file.

*Don't forget to add a reference to itextsharp.dll to your project!!!*


vb.net Code:
''' <summary>
    ''' Add and image as the watermark on each page of the source pdf to create a new pdf with watermark
    ''' </summary>
    ''' <param name="sourceFile">the full path to the source pdf</param>
    ''' <param name="outputFile">the full path where the watermarked pdf will be saved to</param>
    ''' <param name="watermarkImage">the full path to the image file to use as the watermark</param>
    ''' <remarks>The watermark image will be align in the center of each page</remarks>
    Public Shared Sub AddWatermarkImage(ByVal sourceFile As String, ByVal outputFile As String, ByVal watermarkImage As String)
        Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
        Dim stamper As iTextSharp.text.pdf.PdfStamper = Nothing
        Dim img As iTextSharp.text.Image = Nothing
        Dim underContent As iTextSharp.text.pdf.PdfContentByte = Nothing
        Dim rect As iTextSharp.text.Rectangle = Nothing
        Dim X, Y As Single
        Dim pageCount As Integer = 0
        Try
            reader = New iTextSharp.text.pdf.PdfReader(sourceFile)
            rect = reader.GetPageSizeWithRotation(1)
            stamper = New iTextSharp.text.pdf.PdfStamper(reader, New System.IO.FileStream(outputFile, IO.FileMode.Create))
            img = iTextSharp.text.Image.GetInstance(watermarkImage)
            If img.Width > rect.Width OrElse img.Height > rect.Height Then
                img.ScaleToFit(rect.Width, rect.Height)
                X = (rect.Width - img.ScaledWidth) / 2
                Y = (rect.Height - img.ScaledHeight) / 2
            Else
                X = (rect.Width - img.Width) / 2
                Y = (rect.Height - img.Height) / 2
            End If
            img.SetAbsolutePosition(X, Y)
            pageCount = reader.NumberOfPages()
            For i As Integer = 1 To pageCount
                underContent = stamper.GetUnderContent(i)
                underContent.AddImage(img)
            Next
            stamper.Close()
            reader.Close()
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
     ''' <summary>
    ''' Add text as the watermark to each page of the source pdf to create a new pdf with text watermark
    ''' </summary>
    ''' <param name="sourceFile">the full path to the source pdf file</param>
    ''' <param name="outputFile">the full path where the watermarked pdf file will be saved to</param>
    ''' <param name="watermarkText">the text to use as the watermark</param>
    ''' <param name="watermarkFont">the font to use for the watermark. The default font is HELVETICA</param>
    ''' <param name="watermarkFontSize">the size of the font. The default size is 48</param>
    ''' <param name="watermarkFontColor">the color of the watermark. The default color is blue</param>
    ''' <param name="watermarkFontOpacity">the opacity of the watermark. The default opacity is 0.3</param>
    ''' <param name="watermarkRotation">the rotation in degree of the watermark. The default rotation is 45 degree</param>
    ''' <remarks></remarks>
    Public Shared Sub AddWatermarkText(ByVal sourceFile As String, ByVal outputFile As String, ByVal watermarkText As String, _
                                       Optional ByVal watermarkFont As iTextSharp.text.pdf.BaseFont = Nothing, _
                                       Optional ByVal watermarkFontSize As Single = 48, _
                                       Optional ByVal watermarkFontColor As iTextSharp.text.Color = Nothing, _
                                       Optional ByVal watermarkFontOpacity As Single = 0.3F, _
                                       Optional ByVal watermarkRotation As Single = 45.0F)
         Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
        Dim stamper As iTextSharp.text.pdf.PdfStamper = Nothing
        Dim gstate As iTextSharp.text.pdf.PdfGState = Nothing
        Dim underContent As iTextSharp.text.pdf.PdfContentByte = Nothing
        Dim rect As iTextSharp.text.Rectangle = Nothing
         Dim pageCount As Integer = 0
        Try
            reader = New iTextSharp.text.pdf.PdfReader(sourceFile)
            rect = reader.GetPageSizeWithRotation(1)
            stamper = New iTextSharp.text.pdf.PdfStamper(reader, New System.IO.FileStream(outputFile, IO.FileMode.Create))
            If watermarkFont Is Nothing Then
                watermarkFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA, _
                                                              iTextSharp.text.pdf.BaseFont.CP1252, _
                                                              iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED)
            End If
            If watermarkFontColor Is Nothing Then
                watermarkFontColor = iTextSharp.text.Color.BLUE
            End If
            gstate = New iTextSharp.text.pdf.PdfGState()
            gstate.FillOpacity = watermarkFontOpacity
            gstate.StrokeOpacity = watermarkFontOpacity
            pageCount = reader.NumberOfPages()
            For i As Integer = 1 To pageCount
                underContent = stamper.GetUnderContent(i)
                With underContent
                    .SaveState()
                    .SetGState(gstate)
                    .SetColorFill(watermarkFontColor)
                    .BeginText()
                    .SetFontAndSize(watermarkFont, watermarkFontSize)
                    .SetTextMatrix(30, 30)
                    .ShowTextAligned(iTextSharp.text.Element.ALIGN_CENTER, watermarkText, rect.Width / 2, rect.Height / 2, watermarkRotation)
                    .EndText()
                    .RestoreState()
                End With
            Next
            stamper.Close()
            reader.Close()
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

----------


## stanav

This is the updated subroutine for adding multiple text line watermark to pdf pages. The number of lines depending on the number of elements in the string array watermarkText() you pass in.


vb.net Code:
''' <summary>
    ''' Add text as the watermark to each page of the source pdf to create a new pdf with text watermark
    ''' </summary>
    ''' <param name="sourceFile">the full path to the source pdf file</param>
    ''' <param name="outputFile">the full path where the watermarked pdf file will be saved to</param>
    ''' <param name="watermarkText">the string array conntaining the text to use as the watermark. Each element is treated as a line in the watermark</param>
    ''' <param name="watermarkFont">the font to use for the watermark. The default font is HELVETICA</param>
    ''' <param name="watermarkFontSize">the size of the font. The default size is 48</param>
    ''' <param name="watermarkFontColor">the color of the watermark. The default color is blue</param>
    ''' <param name="watermarkFontOpacity">the opacity of the watermark. The default opacity is 0.3</param>
    ''' <param name="watermarkRotation">the rotation in degree of the watermark. The default rotation is 45 degree</param>
    ''' <remarks></remarks>
    Public Shared Sub AddWatermarkText(ByVal sourceFile As String, ByVal outputFile As String, ByVal watermarkText() As String, _
                                       Optional ByVal watermarkFont As iTextSharp.text.pdf.BaseFont = Nothing, _
                                       Optional ByVal watermarkFontSize As Single = 48, _
                                       Optional ByVal watermarkFontColor As iTextSharp.text.Color = Nothing, _
                                       Optional ByVal watermarkFontOpacity As Single = 0.3F, _
                                       Optional ByVal watermarkRotation As Single = 45.0F)
         Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
        Dim stamper As iTextSharp.text.pdf.PdfStamper = Nothing
        Dim gstate As iTextSharp.text.pdf.PdfGState = Nothing
        Dim underContent As iTextSharp.text.pdf.PdfContentByte = Nothing
        Dim rect As iTextSharp.text.Rectangle = Nothing
        Dim currentY As Single = 0.0F
        Dim offset As Single = 0.0F
        Dim pageCount As Integer = 0
        Try
            reader = New iTextSharp.text.pdf.PdfReader(sourceFile)
            rect = reader.GetPageSizeWithRotation(1)
            stamper = New iTextSharp.text.pdf.PdfStamper(reader, New System.IO.FileStream(outputFile, IO.FileMode.Create))
            If watermarkFont Is Nothing Then
                watermarkFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA, _
                                                              iTextSharp.text.pdf.BaseFont.CP1252, _
                                                              iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED)
            End If
            If watermarkFontColor Is Nothing Then
                watermarkFontColor = iTextSharp.text.Color.BLUE
            End If
            gstate = New iTextSharp.text.pdf.PdfGState()
            gstate.FillOpacity = watermarkFontOpacity
            gstate.StrokeOpacity = watermarkFontOpacity
            pageCount = reader.NumberOfPages()
            For i As Integer = 1 To pageCount
                underContent = stamper.GetOverContent(i)
                With underContent
                    .SaveState()
                    .SetGState(gstate)
                    .SetColorFill(watermarkFontColor)
                    .BeginText()
                    .SetFontAndSize(watermarkFont, watermarkFontSize)
                    .SetTextMatrix(30, 30)
                    If watermarkText.Length > 1 Then
                        currentY = (rect.Height / 2) + ((watermarkFontSize * watermarkText.Length) / 2)
                    Else
                        currentY = (rect.Height / 2)
                    End If
                    For j As Integer = 0 To watermarkText.Length - 1
                        If j > 0 Then
                            offset = (j * watermarkFontSize) + (watermarkFontSize / 4) * j
                        Else
                            offset = 0.0F
                        End If
                        .ShowTextAligned(iTextSharp.text.Element.ALIGN_CENTER, watermarkText(j), rect.Width / 2, currentY - offset, watermarkRotation)
                    Next
                    .EndText()
                    .RestoreState()
                End With
            Next
            stamper.Close()
            reader.Close()
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

----------


## WrongWayRookie

Thanks for the code. I'm very new to iTextSHarp.

----------


## WrongWayRookie

How do I get CRLF in to the document? All of the code is on a single line.

Thanks for your help :Confused:

----------


## stanav

> How do I get CRLF in to the document? All of the code is on a single line.
> 
> Thanks for your help


Use the overloaded AddWatermrtkText sub in post #2 which you pass in a string array instead of a single string. Each element in your string array will be rendered as a line in the watermark.

----------


## anwar_khan

hi this really a nice code but the prob lem with i don't wanna create another file i wanna put water mark on exssiting file and dispaly it plz help how can i do this 

thanks
anwar khan

----------


## stanav

The reason why you have to create another file is that when you open the original file for reading, it's being used and you can not write to it. Having said that, you can simply create a new temp file, and once done, you delete the original and rename the temp file to the original's name. This can be done with just a few lines of extra code.

----------


## anwar_khan

thanks for the reply can you give me code how can do it or basically i am doing i am showing a pdf file in asp.net page what my requirement is that when user clikc on print then the watermark put on that file and print it can we do that 

thanks
anwar khan

----------


## stanav

> thanks for the reply can you give me code how can do it or basically i am doing i am showing a pdf file in asp.net page what my requirement is that when user clikc on print then the watermark put on that file and print it can we do that 
> 
> thanks
> anwar khan


That's beyond the scope of this thread. You should post your question in asp.net forum... However, you might have to reconsider your logics. When you show a non-watermarked pdf to the user, the user can just print that version (using the print button in Adobe Reader) or save it to their computer instead of clicking on your print button to print a watermarked pdf.

----------


## pessi

Excellent code. I use it to create an online application.

I made it in asp.net using c#

http://watermark-images.com/pdf-watermark.aspx

----------


## stanav

> Excellent code. I use it to create an online application.
> 
> I made it in asp.net using c#
> 
> http://watermark-images.com/pdf-watermark.aspx


Nice website... Keep up the good work  :Thumb:

----------


## pessi

Thank you. I am in the process of building 10 more nice applications that can be of use to lot of people.

----------


## BigJRofC

This is excellent code and this is what i needed. BTW, I have question if this is possible, can the watermark appear behind page?

Thanks

----------


## stanav

> This is excellent code and this is what i needed. BTW, I have question if this is possible, can the watermark appear behind page?
> 
> Thanks


Yes, in the code I posted, the water mark is written to the over content of the page... This will ensure that the water mark will always be visible (even when the page contains an image, for example). If your page contains mostly text, it is recommended to put the water mark on the under content of the page instead. All you have to do is changing this line:


```
underContent = stamper.GetOverContent(i)
```

To this


```
underContent = stamper.GetUnderContent(i)
```

The rest of the code remains unchanged.

----------


## BigJRofC

Thanks, Stanav. This is great...

----------


## gnoter

For those of us who find this solution via a web search and want a C# (C-Sharp) version, here it is, tested and working.

Foremost: Major thx to stanav; excellent post.

You'll note there are 2 functions, with the first functions calling the second function.  This mimics the "OPTIONAL" params in VB


C-Sharp Code:
public static void AddWatermarkTextC(string sourceFile, string outputFile, string[] watermarkText)
  {
    iTextSharp.text.pdf.BaseFont tWatermarkFont = null;
    float tWatermarkFontSize = 48F;
    iTextSharp.text.Color tWatermarkFontColor = null;
    float tWatermarkFontOpacity = 0.3F;
    float tWatermarkRotation = 45.0F;
     tWatermarkFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);
    tWatermarkFontColor = iTextSharp.text.Color.BLUE;
    AddWatermarkTextC(sourceFile, outputFile, watermarkText, tWatermarkFont, tWatermarkFontSize, tWatermarkFontColor, tWatermarkFontOpacity, tWatermarkRotation);
  }//void AddWatermarkTextC(string sourceFile, string outputFile, string[] watermarkText )
    public static void AddWatermarkTextC(string sourceFile, string outputFile, string[] watermarkText, iTextSharp.text.pdf.BaseFont watermarkFont, float watermarkFontSize, iTextSharp.text.Color watermarkFontColor, float watermarkFontOpacity, float watermarkRotation)
  {
     iTextSharp.text.pdf.PdfReader reader = null;
    iTextSharp.text.pdf.PdfStamper stamper = null;
    iTextSharp.text.pdf.PdfGState gstate = null;
    iTextSharp.text.pdf.PdfContentByte underContent = null;
    iTextSharp.text.Rectangle rect = null;
    float currentY = 0.0F;
    float offset = 0.0F;
    int pageCount = 0;
     try
    {
      reader = new iTextSharp.text.pdf.PdfReader(sourceFile);
      rect = reader.GetPageSizeWithRotation(1);
      stamper = new iTextSharp.text.pdf.PdfStamper(reader, new System.IO.FileStream(outputFile, System.IO.FileMode.Create));
      if (watermarkFont == null)
      {
        watermarkFont = iTextSharp.text.pdf.BaseFont.CreateFont(iTextSharp.text.pdf.BaseFont.HELVETICA, iTextSharp.text.pdf.BaseFont.CP1252, iTextSharp.text.pdf.BaseFont.NOT_EMBEDDED);
      }//if (watermarkFont == null)
       if (watermarkFontColor == null)
      {
        watermarkFontColor = iTextSharp.text.Color.BLUE;
      }//if (watermarkFontColor == null)
       gstate = new iTextSharp.text.pdf.PdfGState();
      gstate.FillOpacity = watermarkFontOpacity;
      gstate.StrokeOpacity = watermarkFontOpacity;
      pageCount = reader.NumberOfPages;
      for (int i = 1; i <= pageCount; i++)
      {
        underContent = stamper.GetOverContent(i);
        underContent.SaveState();
        underContent.SetGState(gstate);
        underContent.SetColorFill(watermarkFontColor);
        underContent.BeginText();
        underContent.SetFontAndSize(watermarkFont, watermarkFontSize);
        underContent.SetTextMatrix(30, 30);
        if (watermarkText.Length > 1)
        {
          currentY = (rect.Height / 2) + ((watermarkFontSize * watermarkText.Length) / 2);
        }//if (watermarkText.Length > 1)
        else
        {
          currentY = (rect.Height / 2);
        }//else if (watermarkText.Length > 1)
         for (int j = 0; j < watermarkText.Length; j++)
        {
          if (j > 0)
          {
            offset = (j * watermarkFontSize) + (watermarkFontSize / 4) * j;
          }//if (j > 0)
          else
          {
            offset = 0.0F;
          }//else if (j > 0)
           underContent.ShowTextAligned(iTextSharp.text.Element.ALIGN_CENTER, watermarkText[j], rect.Width / 2, currentY - offset, watermarkRotation);
        }//for (int j = 0; j < watermarkText.Length; j++)
         underContent.EndText();
        underContent.RestoreState();
      }//for (int i = 1; i <= pageCount; i++)
       stamper.Close();
      reader.Close();
    }
    catch (Exception ex)
    {
      throw ex;
    }
  }//void AddWatermarkTextC(string sourceFile, string outputFile, string[] watermarkText, iTextSharp.text.pdf.BaseFont watermarkFont, float watermarkFontSize, iTextSharp.text.Color watermarkFontColor, float watermarkFontOpacity, float watermarkRotation)

Signed,

MacSpudster / GNoter
==
 :Cool:  *ASPX* = *A*pple *S*imply *P*erforms e*X*cellently   :Cool:

----------


## BigJRofC

Hi Stanav,

I want to use Arial 8 pt in size font base. How to change the font name? Thanks in advance.

Regards,
Buddy

----------


## gnoter

Buddy,

  Dim MyNewFont As iTextSharp.text.Font = iTextSharp.text.FontFactory.GetFont(FontNameSTRING, FontSizeINT)

where FontNameSTRING = "Arial" and FontSizeINT = 8

such as 

  Dim Arial8Plain As iTextSharp.text.Font = iTextSharp.text.FontFactory.GetFont("Arial", 8)

Then use the variable *Arial8Plain* where you'd like.

Signed,

MacSpudster / GNoter
==
 :Cool:  *ASPX* = *Apple Simply Performs eXcellently*  :Cool:

----------


## BigJRofC

Thanks, MacSpudster.

What I need to do, instead of using Helvetica on the above code of Stanav I will use Arial font as a Base Font of the text in my watermark.

Regards,
Buddy

----------


## slow&steady

Hi 

i want to get the following  font 
"Heading 1+93 pt, Bold, Outlined, Black, Times New Roman"
when i declared like below

Dim TNR_93 As iTextSharp.text.Font = iTextSharp.text.FontFactory.GetFont("TimesNewRoman", 93) 

and pass it at watermarkFont like this 

AddWatermarkText(FileName, Path & "\" & Fname(0) & "_WTRMK." & Fname(1), Ptext, TNR_93) 

i am getting error like this

""Value of type 'iTextSharp.text.Font' cannot be converted  'iTextSharp.text.pdf.BaseFont'""

Please Help me 

its very urgent !!!!!!!!!!

Thanks in advance 

Sri

----------


## slow&steady

One more question is 

I want to watermark two lines 

one with fontsize 93 and other with 14 

also i want to include the date on the Topleft and company logo on topright

is it possible ?

i tried with the above code it is overwriting , instead of having all 

Can anybody suggest how to do it 

Thanks in advance,

Sri

----------


## kpmsivachand

> One more question is 
> 
> I want to watermark two lines 
> 
> one with fontsize 93 and other with 14 
> 
> also i want to include the date on the Topleft and company logo on topright
> 
> is it possible ?
> ...


May be my project will helpful to you : http://www.softpedia.com/get/Office-...xploiter.shtml

Just take a screen shot which u want like (one with fontsize 93 and other with 14 etc) and use second option as watermark by image method and do it

Hope it helpful!

----------


## hackerspk

well done

----------


## BigJRofC

Hi Everyone,

I have a project the will place a watermark in existing PDF file. I want to use the code of Stanav unfortunately I think I can't use it. 

What I want to do is use the Agaramond-Pro font for the text and the data that I'm going to insert has italic data in between of the normal text? Can we use the chunk function in watermark (e.g. Sample is _italic_ data)?


Thanks and Regards,
BigJRofC

----------


## marlfera

hi everyone , can you post the sample project using this code.
Please post the link were i can download the sample project for this topic.

thanks and more power.

----------


## keshavkumar

Thanks a lot Stanav !!!!
I was looking for this solution since a long time.
I have used the watermark code to display page number in the existing pdf files.
Thanks to noter also for converting the code to C#.
Thanks once again Stanav... G :Thumb:

----------


## ChristinaHooper

This has been soooo helpful in a project that I've been working on.  

One question though, is it possible to move the stamp so that it's not right in the center of the page?

----------


## BigJRofC

Hi Anyone,

How could I put greek data in watermark? See below data in bold data

...en *ü*ber sample*μ*rbeit

Thanks,

BigJRofC

----------


## hasan_0034

Hi Everybody,

I pasted the code in my VB-Project. But i got an error with the description "The typ iTextSharp.text.Color is not defined".

I did not change the code from stanav. What should i do? 

Thanks

hasan_0034

----------


## stanav

> Hi Everybody,
> 
> I pasted the code in my VB-Project. But i got an error with the description "The typ iTextSharp.text.Color is not defined".
> 
> I did not change the code from stanav. What should i do? 
> 
> Thanks
> 
> hasan_0034


You need to download iTextSharp from the Internet and then add a reference to iTextSharp.dll to your project. If you don't know how to do that, post a question in VB.Net forums and others will guide you.

----------


## mestrini

@stanav

What about a watermark that shows up only when printing?

I've been looking around the web for several days for a way to add a "Show when printing" watermark to a PDF file as in Adobe Acrobat 9 "Appearance Options" and haven't had any luck even to know if it's implemented or not.  :Frown:

----------


## BigJRofC

Hi Evryone, Where I could get the link to get  the c# version of pdfmanipulation.cs using the itextsharp 4? Thanks

----------


## stanav

> Hi Evryone, Where I could get the link to get  the c# version of pdfmanipulation.cs using the itextsharp 4? Thanks


You can always use a VB to C# converter. This one, for example:
http://www.developerfusion.com/tools.../vb-to-csharp/

----------


## mestrini

> @stanav
> 
> What about a watermark that shows up only when printing?
> 
> I've been looking around the web for several days for a way to add a "Show when printing" watermark to a PDF file as in Adobe Acrobat 9 "Appearance Options" and haven't had any luck even to know if it's implemented or not.



Done it by myself.  :wave: 

Even if not replying my request, at least I thank you for posting your code that got me started.

----------

