How to add header and footer in iTextSharp

When you wish to display the page number and a title on every page, you need to make use of the PageEvents from the iTextSharp document settings. Create a class called: ITextEvents.cs with the following structure:

public class ITextEvents : PdfPageEventHelper

        // This is the contentbyte object of the writer
        PdfContentByte cb;

        // we will put the final number of pages in a template
        PdfTemplate headerTemplate, footerTemplate;

        // this is the BaseFont we are going to use for the header / footer
        BaseFont bf = null;

        // This keeps track of the creation time
        DateTime PrintTime = DateTime.Now;

        #region Fields
        private string _header;

        #region Properties
        public string Header
            get { return _header; }
            set { _header = value; }

        public override void OnOpenDocument(PdfWriter writer, Document document)
                PrintTime = DateTime.Now;
                bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                cb = writer.DirectContent;
                headerTemplate = cb.CreateTemplate(100, 100);
                footerTemplate = cb.CreateTemplate(50, 50);
            catch (DocumentException de)

            catch (System.IO.IOException ioe)


        public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
            base.OnEndPage(writer, document);

            iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);

            iTextSharp.text.Font baseFontBig = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);

            Phrase p1Header = new Phrase("Sample Header Here", baseFontNormal);

            //Create PdfTable object
            PdfPTable pdfTab = new PdfPTable(3);

            //We will have to create separate cells to include image logo and 2 separate strings
            //Row 1
            PdfPCell pdfCell1 = new PdfPCell();
            PdfPCell pdfCell2 = new PdfPCell(p1Header);
            PdfPCell pdfCell3 = new PdfPCell();
            String text = "Page " + writer.PageNumber + " of ";

            //Add paging to header
                cb.SetFontAndSize(bf, 12);
                cb.SetTextMatrix(document.PageSize.GetRight(200), document.PageSize.GetTop(45));
                float len = bf.GetWidthPoint(text, 12);
                //Adds "12" in Page 1 of 12
                cb.AddTemplate(headerTemplate, document.PageSize.GetRight(200) + len, document.PageSize.GetTop(45));
            //Add paging to footer
                cb.SetFontAndSize(bf, 12);
                cb.SetTextMatrix(document.PageSize.GetRight(180), document.PageSize.GetBottom(30));
                float len = bf.GetWidthPoint(text, 12);
                cb.AddTemplate(footerTemplate, document.PageSize.GetRight(180) + len, document.PageSize.GetBottom(30));
            //Row 2
            PdfPCell pdfCell4 = new PdfPCell(new Phrase("Sub Header Description", baseFontNormal));
            //Row 3

            PdfPCell pdfCell5 = new PdfPCell(new Phrase("Date:" + PrintTime.ToShortDateString(), baseFontBig));
            PdfPCell pdfCell6 = new PdfPCell();
            PdfPCell pdfCell7 = new PdfPCell(new Phrase("TIME:" + string.Format("{0:t}", DateTime.Now), baseFontBig));

            //set the alignment of all three cells and set border to 0
            pdfCell1.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell2.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell3.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell4.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell5.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell6.HorizontalAlignment = Element.ALIGN_CENTER;
            pdfCell7.HorizontalAlignment = Element.ALIGN_CENTER;

            pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM;
            pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE;
            pdfCell4.VerticalAlignment = Element.ALIGN_TOP;
            pdfCell5.VerticalAlignment = Element.ALIGN_MIDDLE;
            pdfCell6.VerticalAlignment = Element.ALIGN_MIDDLE;
            pdfCell7.VerticalAlignment = Element.ALIGN_MIDDLE;

            pdfCell4.Colspan = 3;

            pdfCell1.Border = 0;
            pdfCell2.Border = 0;
            pdfCell3.Border = 0;
            pdfCell4.Border = 0;
            pdfCell5.Border = 0;
            pdfCell6.Border = 0;
            pdfCell7.Border = 0;

            //add all three cells into PdfTable

            pdfTab.TotalWidth = document.PageSize.Width - 80f;
            pdfTab.WidthPercentage = 70;
            //pdfTab.HorizontalAlignment = Element.ALIGN_CENTER;

            //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
            //first param is start row. -1 indicates there is no end row and all the rows to be included to write
            //Third and fourth param is x and y position to start writing
            pdfTab.WriteSelectedRows(0, -1, 40, document.PageSize.Height - 30, writer.DirectContent);
            //set pdfContent value

            //Move the pointer and draw line to separate header section from rest of page
            cb.MoveTo(40, document.PageSize.Height - 100);
            cb.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 100);

            //Move the pointer and draw line to separate footer section from rest of page
            cb.MoveTo(40, document.PageSize.GetBottom(50) );
            cb.LineTo(document.PageSize.Width - 40, document.PageSize.GetBottom(50));

        public override void OnCloseDocument(PdfWriter writer, Document document)
            base.OnCloseDocument(writer, document);

            headerTemplate.SetFontAndSize(bf, 12);
            headerTemplate.SetTextMatrix(0, 0);
            headerTemplate.ShowText((writer.PageNumber - 1).ToString());

            footerTemplate.SetFontAndSize(bf, 12);
            footerTemplate.SetTextMatrix(0, 0);
            footerTemplate.ShowText((writer.PageNumber - 1).ToString());


The calling function looks like this:

private void CreatePDF()
            string fileName = string.Empty;

            DateTime fileCreationDatetime = DateTime.Now;

            fileName = string.Format("{0}.pdf", fileCreationDatetime.ToString(@"yyyyMMdd") + "_" + fileCreationDatetime.ToString(@"HHmmss"));

            string pdfPath = Server.MapPath(@"~PDFs") +   fileName;

            using (FileStream msReport = new FileStream(pdfPath, FileMode.Create))
                //step 1
                using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 140f, 10f))
                        // step 2
                        PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, msReport);
                        pdfWriter.PageEvent = new Common.ITextEvents();

                        //open the stream

                        for (int i = 0; i < 10; i++)
                            Paragraph para = new Paragraph("Hello world. Checking Header Footer", new Font(Font.FontFamily.HELVETICA, 22));

                            para.Alignment = Element.ALIGN_CENTER;




                    catch (Exception ex)
                        //handle exception





Save images from PDF Files using iTextSharp

This code will allow you to go through a PDF Document and extract the images.

public void ExtractImagesFromPDF(string sourcePdf, string outputPath) {
  // NOTE: This will only get the first image it finds per page.
  PdfReader pdf = new PdfReader(sourcePdf);
  RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf);

  try {
   for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++) {
    Response.Write("Page " + pageNumber.ToString());
    PdfDictionary pg = pdf.GetPageN(pageNumber);
    // recursively search pages, forms and groups for images.
    PdfObject obj = FindImageInPDFDictionary(pg);
    if (obj != null) {
     int XrefIndex = Convert.ToInt32(((PRIndirectReference) obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
     PdfObject pdfObj = pdf.GetPdfObject(XrefIndex);
     PdfStream pdfStrem = (PdfStream) pdfObj;
     byte[] bytes = PdfReader.GetStreamBytesRaw((PRStream) pdfStrem);
     if ((bytes != null)) {
      using(System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes)) {
       memStream.Position = 0;
       System.Drawing.Image img = System.Drawing.Image.FromStream(memStream);
       // must save the file while stream is open.
       if (!Directory.Exists(outputPath))
       string path = Path.Combine(outputPath, String.Format(@ "{0}.jpg", pageNumber));
       System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1);
       parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0);
       ImageCodecInfo jpegEncoder = GetEncoder(ImageFormat.Jpeg);
       img.Save(path, jpegEncoder, parms);



    } else {
Page " + pageNumber.ToString() + " has no images!");

  } catch {

  } finally {


 // This method will allow you to detect an image in a PDF page
private PdfObject FindImageInPDFDictionary(PdfDictionary pg) {
 PdfDictionary res =
  (PdfDictionary) PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
 PdfDictionary xobj =
  (PdfDictionary) PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
 if (xobj != null) {
  foreach(PdfName name in xobj.Keys) {
   PdfObject obj = xobj.Get(name);
   if (obj.IsIndirect()) {
    PdfDictionary tg = (PdfDictionary) PdfReader.GetPdfObject(obj);
    PdfName type =
     (PdfName) PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
    //image at the root of the pdf
    if (PdfName.IMAGE.Equals(type)) {
     return obj;

    } // image inside a form
    else if (PdfName.FORM.Equals(type)) {
     return FindImageInPDFDictionary(tg);

    } //image inside a group
    else if (PdfName.GROUP.Equals(type)) {
     return FindImageInPDFDictionary(tg);



 return null;


If you are using ImageCodecInfo

private ImageCodecInfo GetEncoder(ImageFormat format) {
 ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
 foreach(ImageCodecInfo codec in codecs) {
  if (codec.FormatID == format.Guid) {
   return codec;
 return null;

Writing Articles for Cash

Did you ever want to make quick money? Why not write an article or two for cash. This e-book will show you how to do it.

105“Profitable Writer Finally Reveals ‘Closely Guarded’ Secrets That Can Increase Your Ability To Earn Extra Cash Whenever You Want It!”

Dear Aspiring Earner,

How would you like to learn to use the talent you already have within you to make extra bits of cash anytime you want to? Seem like some sort of “scam” or “pipe dream”? Well, it isn’t. People all across the world do it every single day. And now is your chance to discover what they’re doing and use it to your own money making benefit!

It’s no secret that the Internet is a virtual “hot bed” of information. Millions of people go “info-cruising” every day just to find helpful information. And, many of those people are willing to pay for that information. But, where do you find these people? And how can you ensure they will buy your information?

In Writing For Fast Cash, author [Your Name] reveals how to find a “hot” topic, a “hot” market, and how to combine the two into instantaneous profits by doing something you probably do all the time!

Writing is such a simple way to earn money, you may just bust-a-gut laughing once you read this easy-to-understand-and-implement guide. It is astounding how many people striving to earn money online overlook this! They are always searching for the “easy way out” when it comes to selling things from the comfort of their homes when all the while the easiest and most logical way is right under their noses!

Writing For Fast Cash will tell you all you need to know when it comes to “publishing your way to profits”. When you secure your copy today, you will uncover:

  • How To Unveil Hidden “Gold Mines” Of Profitable Topics Through A Simple “Search System”
  • The 2 Most Profitable Resources Every Person Must Have In Order To Earn And Continue To Earn Fast Cash From Writing
  • The Insanely Easy To Follow Basic Writing Template That Almost Every Single Information Product Abides By
  • Two “Secret” Tricks To Getting The Most Money Out Of Your Writings
  • The ONE Type Of Information Product That Will Always Earn You The Quickest Money Possible
  • And Much More!

To be quite honest with you, this is one guide you must have if you ever want to earn fast cash with any information product. Especially mastering the art of creating the one kind that will almost always make you profits. Your Own!

Download Guide

How to add a multi-page TIFF to a PDF using iTextSharp (VB.NET)

If you are ever stuck with a multi-page tiff, you will know how frustrating it is to get the images out and then add them to a pdf. This code snippet below shows how it’s done and feel free to leave a comment if you have used it and it worked.

'check if image exists
                Dim fi As New FileInfo(strImagePath)
                If fi.Exists Then

                    'save image in document
                    Dim gif As Image = Image.GetInstance(fi.FullName)
                    Dim pageWidth = doc.PageSize.Width - (10 + 10)
                    Dim pageHeight = doc.PageSize.Height - (40 + 10)

                    If fi.Extension.ToLower.EndsWith("tif") Then
                        Dim bmp As New System.Drawing.Bitmap(fi.FullName)
                        Dim total As Integer = bmp.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page)
                        If total > 1 Then
                            For k As Integer = 0 To total - 1
                                bmp.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, k)
                                Dim img As iTextSharp.text.Image
                                img = iTextSharp.text.Image.GetInstance(bmp, System.Drawing.Imaging.ImageFormat.Bmp)
                                img.SetAbsolutePosition(10, 40)
                                img.ScaleToFit(pageWidth, pageHeight)
                        End If
                        gif.SetAbsolutePosition(10, 40)
                        gif.ScaleToFit(pageWidth, pageHeight)

                    End If
                End If
            End If

Splitting PDF pages programatically using ABCPdf 7

As a programmer, you are sometimes faced with the issue of taking one existing PDF and extracting a specific page from it to show to the user. We have been using ABCPDF7 for this which you can download from their website.

Website Link:

First, we import the dlls into the project reference:

Reference Include=”ABCpdf, Version=, Culture=neutral, PublicKeyToken=a7a0b3f5184f2169, processorArchitecture=MSIL”>
<HintPath>…………..Program FilesWebSupergooABCpdf .NET 7.0ABCpdf.DLL</HintPath>

and the namespace at the top of the file. For this example I will be using VB.NET

Imports WebSupergoo.ABCpdf7
Imports WebSupergoo.ABCpdf7.Objects
Imports WebSupergoo.ABCpdf7.Atoms
Imports WebSupergoo.ABCpdf7.Operations

Declaring the source PDF and getting the number of pages:
Dim theSrc As Doc = New Doc()
Dim theCount As Integer = theSrc.PageCount

Pages start their count from 1 which is different from the 0-based arrays in .NET. Now we go through the pages of the document and save each page as a separate PDF file

Dim i As Integer
For i = 1 To theCount
Dim theDst As Doc = New Doc()
theDst.MediaBox.String = theSrc.MediaBox.String

theDst.Rect.String = theDst.MediaBox.String
theDst.Rect.Inset(0, 0)
theDst.Rect.Position(0, 0)
Dim theX As Double, theY As Double
theX = theDst.MediaBox.Width / 2
theY = theDst.MediaBox.Height / 2

theDst.Page = theDst.AddPage()
theDst.Save(Server.MapPath(“result” & CStr(i) & “.pdf”))

The files will be saved in the local folder and will be result1, result2, etc..

If you only want one specific page, PageNumberWanted is the page number starting from 1 and less than the number of pages available (can be retrieved via the count method above). The code is:

Dim theDst As Doc = New Doc()

theDst.MediaBox.String = theSrc.MediaBox.String
theDst.Rect.String = theDst.MediaBox.String
theDst.Rect.Inset(0, 0)
theDst.Rect.Position(0, 0)

theDst.Page = theDst.AddPage()
theDst.AddImageDoc(theSrc, PageNumberWanted, Nothing)

strPath = Server.MapPath(“ReportPageNumberWanted.pdf”)