How do I add a table as a title?

I am working with iTextSharp trying to add a header and footer to my generated PDF, but if I try to add a header 100% wide of my page I run into some problems.

So, I do the following things:

1) I have created a class called PdfHeaderFooter that extends the iTextSharp PdfPageEventHelper class

2) In PdfHeaderFooter, I have implemented the OnStartPage () method that generates the header:

    // write on start of each page
    public override void OnStartPage(PdfWriter writer, Document document)
    {
        base.OnStartPage(writer, document);
        PdfPTable tabHead = new PdfPTable(new float[] { 1F });
        PdfPCell cell;
        //tabHead.TotalWidth = 300F;
        tabHead.WidthPercentage = 100;

        cell = new PdfPCell(new Phrase("Header"));
        tabHead.AddCell(cell);
        tabHead.WriteSelectedRows(0, -1, 150, document.Top, writer.DirectContent);
    }

      

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

The table width must be greater than zero.

Why? What is the problem? How is it possible that the table is of size 0 if I set it to 100%?

Can anyone help me to solve this problem?

Tpx

0


source to share


1 answer


When used, it writeSelectedRows()

doesn't make sense to set the percentage of the width to 100%. Setting a percentage of width means when you add a document using document.add()

(which is a method that cannot be used on a page event). When using document.add()

iText, calculates table width based on page size and margins.

You are using writeSelectedRows()

, which means that you are responsible for determining the size and coordinates of the table.

If you want the table to span the full width of the page, you need:

table.TotalWidth = document.Right - document.Left;

      



You are also using the wrong X coordinate: you must use document.Left

instead 150

.

Additional Information:

  • The first two parameters define the start line and end line. In your case, you start at line 0, which is the first line, and you do not define an ending line (which means -1), in which case all lines are drawn.
  • You missed parameters for columns (there is an option writeSelectedRows()

    that expects 7 parameters).
  • Then you have the X and Y value of the starting coordinate for the table.
  • Finally, you pass the instance PdfContentByte

    . This is the canvas on which you draw the table.
+6


source







All Articles