Skip to main content
Skip table of contents

How to add a table as a header?

I am working with iTextSharp trying to add an header and a footer to my generated PDF, but if I try to add an header that have width of 100% of my page I have some problem.

  1. I have create a class named PdfHeaderFooter that extends the iTextSharp PdfPageEventHelper class,
  2. into PdfHeaderFooter I have implemented the OnStartPage() method that generate the header:

public override void OnStartPage(PdfWriter writer, Document document) {
    base.OnStartPage(writer, document);
    PdfPTable tabHead = new PdfPTable(new float[] { 1F });
    PdfPCell cell;
    tabHead.WidthPercentage = 100;
    cell = new PdfPCell(new Phrase("Header"));
    tabHead.WriteSelectedRows(0, -1, 150, document.Top, writer.DirectContent);

If I use something like tabHead.TotalWidth = 300F; instead of tabHead.WidthPercentage = 100;, it works well, but if I try to set as 100% the width of the tabHead table (as I do in the previous example) when it call the tabHead.WriteSelectedRows(0, -1, 150, document.Top, writer.DirectContent) method it throws the following exception:

The table width must be greater than zero.

Why? What is the problem? How is it possible that the table have 0 size if I am setting it to 100%?

Posted on StackOverflow on Mar 12, 2014 by AndreaNobili

Please, take a look at the TableHeader example for iText 7. We implement IEventHandler interface so that the table will have the full width of your page. This is done using setWidth() method.

Note that setWidthPercent() won't work in your case, because setting the width percentage is meant for when you add a document using document.add() (which is a method you can't use in a page event). When using document.add(), iText calculates the width of the table based on the page size and the margins.

Also beware of adding event handlers in the START_PAGE event. Use END_PAGE instead. And don't forget to set the document margins after creating a header:

TableHeaderEventHandler handler = new TableHeaderEventHandler(doc);
pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, handler);
doc.setMargins(20 + handler.getTableHeight(), 36, 36, 36);

Click this link if you want to see how to answer this question in iText 5.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.