BlueLemonCode.Com

Yet Another Tech Blog

Using iTextSharp with asp.net to add watermark in pdf file

Introduction

In my previous articles about use of iTextSharp in dealing with pdf files, I demonstrated how to create a pdf when text/file is provided. I also tried to explain about adding header in the pdf files here.

In this short article, I will try to elaborate how easily you can add watermark text/image in the pdf files.

Background

For legal/professional purpose, it is generally required to add a watermark text in all pdf files before releasing it to intended audience. Many third party tools are available with such feature. But it takes few lines of code to do the same thing using iTextSharp.

Article Body

For test purpose, I have hard coded source and output file names in below code. You might want to pass input/output file path as parameter to function or iterate through given folder and process all pdf files present in that folder.

I am leaving the other processing part and keeping focus on adding watermark.

To start with, download and add reference to iTextSharp dll in your project (if unsure, please read my first post here). Import following namespace information at top of page

using iTextSharp.text;
using iTextSharp.text.pdf;

Below is complete code which reads source pdf file, modifies pdf content and saves modified content in another file stream

C#

        //create pdfreader object to read sorce pdf
        PdfReader pdfReader=new PdfReader(Server.MapPath("Input") + "/" + "input.pdf");
        //create stream of filestream or memorystream etc. to create output file
        FileStream stream = new FileStream(Server.MapPath("Output") + "/output.pdf", FileMode.OpenOrCreate);
        //create pdfstamper object which is used to add addtional content to source pdf file
        PdfStamper pdfStamper = new PdfStamper(pdfReader,stream);
        //iterate through all pages in source pdf
        for (int pageIndex = 1; pageIndex <= pdfReader.NumberOfPages; pageIndex++)
        {
            //Rectangle class in iText represent geomatric representation... in this case, rectanle object would contain page geomatry
            Rectangle pageRectangle = pdfReader.GetPageSizeWithRotation(pageIndex);
            //pdfcontentbyte object contains graphics and text content of page returned by pdfstamper
            PdfContentByte pdfData = pdfStamper.GetUnderContent(pageIndex);
            //create fontsize for watermark
            pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 40);
            //create new graphics state and assign opacity
            PdfGState graphicsState = new PdfGState();
            graphicsState.FillOpacity = 0.4F;
            //set graphics state to pdfcontentbyte
            pdfData.SetGState(graphicsState);
            //set color of watermark
            pdfData.SetColorFill(BaseColor.BLUE);
            //indicates start of writing of text
            pdfData.BeginText();
            //show text as per position and rotation
            pdfData.ShowTextAligned(Element.ALIGN_CENTER, "BlueLemonCode", pageRectangle.Width / 2, pageRectangle.Height / 2, 45);
            //call endText to invalid font set
            pdfData.EndText();
        }
        //close stamper and output filestream
        pdfStamper.Close();
        stream.Close();

VB.Net

'create pdfreader object to read sorce pdf
Dim pdfReader As New PdfReader(Server.MapPath("Input") & "/" & "input.pdf")
'create stream of filestream or memorystream etc. to create output file
Dim stream As New FileStream(Server.MapPath("Output") & "/output.pdf", FileMode.OpenOrCreate)
'create pdfstamper object which is used to add addtional content to source pdf file
Dim pdfStamper As New PdfStamper(pdfReader, stream)
'iterate through all pages in source pdf
For pageIndex As Integer = 1 To pdfReader.NumberOfPages
	'Rectangle class in iText represent geomatric representation... in this case, rectanle object would contain page geomatry
	Dim pageRectangle As Rectangle = pdfReader.GetPageSizeWithRotation(pageIndex)
	'pdfcontentbyte object contains graphics and text content of page returned by pdfstamper
	Dim pdfData As PdfContentByte = pdfStamper.GetUnderContent(pageIndex)
	'create fontsize for watermark
	pdfData.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 40)
	'create new graphics state and assign opacity
	Dim graphicsState As New PdfGState()
	graphicsState.FillOpacity = 0.4F
	'set graphics state to pdfcontentbyte
	pdfData.SetGState(graphicsState)
	'set color of watermark
	pdfData.SetColorFill(BaseColor.BLUE)
	'indicates start of writing of text
	pdfData.BeginText()
	'show text as per position and rotation
	pdfData.ShowTextAligned(Element.ALIGN_CENTER, "BlueLemonCode", pageRectangle.Width / 2, pageRectangle.Height / 2, 45)
	'call endText to invalid font set
	pdfData.EndText()
Next
'close stamper and output filestream
pdfStamper.Close()
stream.Close()

Little more about the code used

The object of PDFStamper class is used to apply new content into source pdf file (stamp data). PDFContentByte is used to hold text and graphic content of page; using which we can set the color/font of text and add data in pdf file.

graphicsState.FillOpacity property is used to set opacity of watermark text. Lower the opacity factor more transparant the watermark would be.

Modify the below line of code to position watermark text at required location in pdf page

pdfData.ShowTextAligned(Element.ALIGN_CENTER, "BlueLemonCode", pageRectangle.Width / 2, pageRectangle.Height / 2, 45)

The parameter are in following sequence. Alignment type, watermark text, X position, Y position, angle of rotation.

After using above line of code in my sample application, This is how watermark is added in my sample pdf file.

You can also add image as watermark instead of simple text by using PDFContentByte class's AddImage method.

Hope this short article and code helps someone :)