title: Setting margins, headers and footers for PDF without overlap
body: <p>I need some help with tweaking my PDF header/footer alongside my text areas. The first page looks okay and it just gets worse from there. Is the header and footer eating into my existing margin spaces?</p>
  
  <p>I would like to know what is going wrong and what I can tweak to set the below:</p>
  
  <ol>
  <li>Page widths</li>
  <li>Margin widths</li>
  <li>Header</li>
  <li>Footer</li>
  <li>Text area</li>
  </ol>
  
  <p><img src="https://i.stack.imgur.com/Mlo0y.png" alt="margins"></p>
  
  <p><img src="https://i.stack.imgur.com/lDOY5.png" alt="PDF"></p>
  
  <p>My header override function is as below:</p>
  
  <pre><code>public partial class Header : PdfPageEventHelper
  {
  public override void OnStartPage(PdfWriter writer, Document doc)
      {
      PdfPTable headerTbl = new PdfPTable(2);
      headerTbl.SetWidths(new float[] { 4, 1 });
      headerTbl.TotalWidth = doc.PageSize.Width;
  
      iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("~/Images/view.gif"));
      logo.ScalePercent(5);
      PdfPCell cell = new PdfPCell(logo);
      cell.HorizontalAlignment = Element.ALIGN_RIGHT;
      cell.PaddingRight = 20;
      cell.Border = Rectangle.NO_BORDER;
  
  
      Font timesH = new Font(Font.FontFamily.TIMES_ROMAN, 20);
      Font times = new Font(Font.FontFamily.TIMES_ROMAN, 10);
      Chunk c1= new Chunk("THIS IS MY HEADER TEXT", timesH);
      Chunk c = new Chunk("\n", times);
      Chunk c2=new Chunk("PLEASE HAVE A NICE DAY", times);
      Phrase p = new Phrase();
      p.Add(c1);
      p.Add(c);
      p.Add(c2);
      PdfPCell cell2 = new PdfPCell(p);
      cell2.Border = Rectangle.NO_BORDER;
  
      headerTbl.AddCell(cell2);
      headerTbl.AddCell(cell);
  
      headerTbl.WriteSelectedRows(0, -1, 0, (doc.PageSize.Height - 10), writer.DirectContent);
  
      }
  }
  </code></pre>
  
  <p>stringWrite is a StringWriter that contains a bunch of data. More clarity <a href="https://stackoverflow.com/questions/23235519/using-itextsharp-to-print-a-pdf-with-multiple-tables">HERE</a>. </p>
  
  <p>I create the pdf as follows: </p>
  
  <pre><code>    StringReader sr = new StringReader(stringWrite.ToString());
      Document pdfDoc = new Document(new Rectangle(288f, 144f), 10f, 10f, 30f, 30f);
      pdfDoc.SetPageSize(PageSize.A4.Rotate());
      HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
      PdfWriter pdfwriter = PdfWriter.GetInstance(pdfDoc, HttpContext.Current.Response.OutputStream);
      pdfwriter.PageEvent = new Footer();
      pdfwriter.PageEvent = new Header();
      pdfDoc.Open();
      htmlparser.Parse(sr);
      pdfDoc.Close();
      HttpContext.Current.Response.Write(pdfDoc);
      HttpContext.Current.Response.End();
  </code></pre>
  
  <p>I'm using iTextSharp, C#, Asp.net in my application.</p>