'how to insert header and footer to existing pdf document using itextsharp (without overriding the existing content of the page)

In my project I am using MVC4,C# and itextsharp to generate pdf from html. I need to insert header with a logo and template name, and footer with paging (page number/Total number of pages). I am done the the footer, I have used this code to add footer to the pdf file:

public static byte[] AddPageNumbers(byte[] pdf)
        {
            MemoryStream ms = new MemoryStream();
            ms.Write(pdf, 0, pdf.Length);
            // we create a reader for a certain document
            PdfReader reader = new PdfReader(pdf);
            // we retrieve the total number of pages
            int n = reader.NumberOfPages;
            // we retrieve the size of the first page
            Rectangle psize = reader.GetPageSize(1);

            // step 1: creation of a document-object
            Document document = new Document(psize, 50, 50, 50, 50);
            // step 2: we create a writer that listens to the document
            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            // step 3: we open the document

            document.Open();
            // step 4: we add content
            PdfContentByte cb = writer.DirectContent;



            int p = 0;
            Console.WriteLine("There are " + n + " pages in the document.");
            for (int page = 1; page <= reader.NumberOfPages; page++)
            {
                document.NewPage();
                p++;
                PdfImportedPage importedPage = writer.GetImportedPage(reader, page);

                cb.AddTemplate(importedPage, 0, 0);

                BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
                cb.BeginText();
                cb.SetFontAndSize(bf, 10);
                cb.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, +p + "/" + n, 44, 7, 0);
                cb.EndText();


            }
            // step 5: we close the document

            document.Close();
            return ms.ToArray();
        }
    }

if you need any explanation about this code please let me know.

I tried to use the same method for header but my site logo is overriding the existing content of the pdf page. Then i tried to use this code but no luck :(

       public _events(string TemplateName,string ImgUrl)
        {
            this.TempName = TemplateName;
            this.ImageUrl = ImgUrl;
        }
        private string TempName = string.Empty;
        private string ImageUrl = string.Empty;

        public override void OnEndPage(PdfWriter writer, Document doc)
        {


            //Paragraph footer = new Paragraph("THANK YOU ", FontFactory.GetFont(FontFactory.TIMES, 10, iTextSharp.text.Font.NORMAL));




            Paragraph header = new Paragraph("Template Name:" + TempName + "                             " +DateTime.UtcNow, FontFactory.GetFont(FontFactory.TIMES, 10, iTextSharp.text.Font.NORMAL));

            //adding image (logo)

            string imageURL = HttpContext.Current.Server.MapPath("~/Content/images.jpg");
            iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);
            //Resize image depend upon your need
            jpg.ScaleToFit(140f, 120f);
            //Give space before image
            jpg.SpacingBefore = 10f;
            //Give some space after the image
            jpg.SpacingAfter = 1f;
            jpg.Alignment = Element.ALIGN_LEFT;


            header.Alignment = Element.ALIGN_TOP;

            PdfPTable headerTbl = new PdfPTable(1);

            headerTbl.TotalWidth = 400;

            headerTbl.HorizontalAlignment = Element.ALIGN_CENTER;

            PdfPCell cell11 = new PdfPCell(header);
            PdfPCell cell2 = new PdfPCell(jpg);
            cell2.Border = 0;
            cell11.Border = 0;

            cell11.PaddingLeft = 10;
            cell2.PaddingLeft = 10;
            headerTbl.AddCell(cell11);
            headerTbl.AddCell(cell2);

            headerTbl.WriteSelectedRows(0, -1, doc.LeftMargin, doc.PageSize.Height - 10, writer.DirectContent);

  }
    }

here is my Action method to which is returning the pdf file as response. and i have used this class in it. apologies may be I should post this in beginning of my question.

[HttpGet]
[HandleException]
public ActionResult GenerateLeadProposalPDF()
{
    TempData.Keep();
    long LeadId = Convert.ToInt64(TempData["Leadid"]);
    long EstimateId = Convert.ToInt64(TempData["Estimateid"]);
    long ProposalTemplateId = Convert.ToInt64(TempData["ProposalTemplateId"]);
    Guid SubscriberId = SessionManagement.LoggedInUser.SubscriberId;
    var data = this._LeadEstimateAPIController.GetLeadProposalDetails(LeadId, EstimateId, ProposalTemplateId, SubscriberId);
    System.Text.StringBuilder strBody = new System.Text.StringBuilder("");
    string SubscriberProjectBody = this.ControllerContext.RenderRazorViewToString(ViewData, TempData, "~/Areas/Subscriber/Views/Shared/_GenerateProposalTemplate.cshtml", data);
    string Header = this.ControllerContext.RenderRazorViewToString(ViewData, TempData, "~/Areas/Subscriber/Views/Shared/_HeaderGenerateProposals.cshtml", data);
    string styleCss = System.IO.File.ReadAllText(Server.MapPath("~/ProposalDoc_CSS.txt"));
    strBody.Append(@"<html><head><title></title>   </head>");
    strBody.Append(@"<body lang=EN-US style='tab-interval:.5in'>");
   // strBody.Append(Header);
    strBody.Append(SubscriberProjectBody);
    strBody.Append(@"</body></html>");
    String htmlText = strBody.ToString();
    Document document3 = new Document(PageSize.A4, 36, 36, 36, 36);
    _events e = new _events(data.objProposalLeadDetailsModel.ProposalFullName,"test");
    string filePath = HostingEnvironment.MapPath("~/");
    filePath = filePath + "pdf-.pdf";
    var stream=new FileStream(filePath, FileMode.Create);
  var objPdfWriter=  PdfWriter.GetInstance(document3, stream);
    document3.Open();
    objPdfWriter.PageEvent = e;
    iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document3);
    hw.Parse(new StringReader(htmlText));
    document3.Close();
    var result = System.IO.File.ReadAllBytes(filePath);
    var abd = new FileStream(filePath, FileMode.Open, FileAccess.Read);

    var streamArray = ReadFully(abd);

    var streamFile = AddPageNumbers(streamArray);




    // Response.End();
    string contentType = "application/pdf";
    return File(streamFile, contentType, "LeadProposal.pdf");
}

I have searched a lot over google, my pdf looks like this the logo is overriding the existing content see

Any suggestion or help will be appreciated, Please help me, thanks in advance :)



Solution 1:[1]

after some changes in the _events class I got what I want, but may be its not the right way to do it, but for now its working for me :)

public class _events : PdfPageEventHelper
    {
        public _events(string TemplateName,string ImgUrl)
        {
            this.TempName = TemplateName;
            this.ImageUrl = ImgUrl;
        }
        private string TempName = string.Empty;
        private string ImageUrl = string.Empty;

        public override void OnEndPage(PdfWriter writer, Document doc)
        {
            Paragraph PTempName = new Paragraph("Template Name:" + TempName, FontFactory.GetFont(FontFactory.TIMES, 10, iTextSharp.text.Font.NORMAL));
            Paragraph PDate = new Paragraph(DateTime.UtcNow.ToShortDateString(), FontFactory.GetFont(FontFactory.TIMES, 10, iTextSharp.text.Font.NORMAL));

            //adding image (logo)

            string imageURL = "http://108.168.203.227/PoologicApp/Content/Bootstrap/images/logo.png";//HttpContext.Current.Server.MapPath("~/Content/images.jpg");
            iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);
            //Resize image depend upon your need
            jpg.ScaleToFit(70f, 120f);
            //Give space before image
            //jpg.SpacingBefore = 10f;
            //Give some space after the image
            jpg.SpacingAfter = 1f;
            jpg.Alignment = Element.ALIGN_TOP;


            PTempName.Alignment = Element.ALIGN_TOP;
            PDate.Alignment = Element.ALIGN_TOP;

            PdfPTable headerTbl = new PdfPTable(3);

            headerTbl.TotalWidth = 600;

            headerTbl.HorizontalAlignment = Element.ALIGN_TOP;

            PdfPCell cell11 = new PdfPCell(PTempName);
            PdfPCell cell3 = new PdfPCell(PDate);
            PdfPCell cell2 = new PdfPCell(jpg);
            cell2.Border = 0;
           cell11.Border = 0;
           cell3.Border = 0;

            cell11.PaddingLeft = 10;
            cell3.PaddingLeft = 10;
            cell2.PaddingLeft = 10;
            headerTbl.AddCell(cell11);
            headerTbl.AddCell(cell3);
            headerTbl.AddCell(cell2);

            headerTbl.WriteSelectedRows(0, -1, doc.LeftMargin, doc.PageSize.Height - 4, writer.DirectContent);


        }
    }

now my pdf looks like this : enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1