Adding watermark to existing PDF files using iTextSharp

This code will take a file as an input from the file system and add a watermark to that file.

    string FileLocation = "c:\\Temp\\SomeFile.pdf";
    string WatermarkLocation = "c:\\Temp\\watermark.gif";

    Document document = new Document();
    PdfReader pdfReader = new PdfReader(FileLocation);
    PdfStamper stamp = new PdfStamper(pdfReader, new FileStream(FileLocation.Replace(".pdf","[temp][file].pdf"), FileMode.Create));

    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(WatermarkLocation);
    img.SetAbsolutePosition(250,300); // set the position in the document where you want the watermark to appear (0,0 = bottom left corner of the page)

    PdfContentByte waterMark;
    for (int page = 1; page <= pdfReader.NumberOfPages; page++)
    {
        waterMark = stamp.GetUnderContent(page);
        waterMark.AddImage(img);
    }
    stamp.FormFlattening = true;
    stamp.Close();

    // now delete the original file and rename the temp file to the original file
    File.Delete(FileLocation);
    File.Move(FileLocation.Replace(".pdf", "[temp][file].pdf"), FileLocation);

For the above to work, you need to make sure that the script has permissions to read and write from the C:\Temp folder. You also need to reference iTextSharp.dll.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.