# Tutorial: iText by Example

## Tables

My First PdfPTable:
If you want to use iText to make bills, invoices, list, reports, etc... you will probably want to present your data in a tabular form. That's why the objects PdfPTable and PdfPCell were created.
Both classes are very easy to use: just construct a table with a certain number of columns and add cells to it:

    PdfPTable table = new PdfPTable(3);
    PdfPCell cell =
      new PdfPCell(new Paragraph("header with colspan 3"));
    cell.setColspan(3);
    table.addCell(cell);
    table.addCell("1.1");
    table.addCell("2.1");
    table.addCell("3.1");
    table.addCell("1.2");
    table.addCell("2.2");
    table.addCell("3.2");
    document.add(table);

The result is the PDF equivalent of the HTML table:

    <table border="1" width="80%" cellpadding="2">
      <tr>
        <td colspan="3">header with colspan 3</td>
      </tr>
      <tr>
        <td>1.1</td>
        <td>1.2</td>
        <td>1.3</td>
      </tr>
      <tr>
        <td>2.1</td>
        <td>2.2</td>
        <td>2.3</td>
      </tr>
    </table>

header with colspan 3
1.1 | 1.2 | 1.3
2.1 | 2.2 | 2.3

Example: java com.lowagie.examples.objects.tables.MyFirstTable
Use a PdfPTable to add a table to a PDF document: see MyFirstTable.pdf
PdfPTable is a very powerful and flexible object, but for some specific needs, you can also use one of the alternatives for PdfPTable. If you have a Swing application with JTables, you can look at the JTable2Pdf section. PdfPTable only works for generating PDF. If you need to generate HTML or RTF, you need the (no longer supported) Table object.
Go to top of the page
Widths, alignment and spacing:
If you add a PdfPTable with Document.add(), the default width of the table is 80 percent of the available space and the table is aligned in the center. You can change these defaults with setWidthPercentage and setHorizontalAlignment.
Example: java com.lowagie.examples.objects.tables.TableWidthAlignment
Changing the width and the alignment of the complete table: see TableWidthAligment.pdf
We have defined the number of columns of the table and based on the widthpercentage, iText calculated an absolute width. The default absolute width of each cell is (absolute width table / number): all cells have the same width. Of course you may want to change this. You can do this in different ways:

- Use another constructor: PdfPTable(float[] relativeWidths). For instance, if you want two 'normal' columns and a third column that's double the size of a 'normal' column, use the float-array {1f, 1f, 2f} as relativewidths. iText will calculate the absolute width for you.
- You can also use the method setWidths to change this array after you constructed the PdfPTable (but be carefull: the array needs to have the same size as the number of columns). In the example the percentages are changed from (10%, 10%, 5%, 75%) to (20%, 20%, 10%, 50%) so the second table looks completely different.
- If you want to work with absolute widths for the columns. You have to let iText calculate a widthpercentage for the table. In this case you should use: setWidthPercentage(float[] columnWidth, Rectangle pageSize). As you can see in the example, you need to do some calculations first to get the right pagesize.
- It even easier to use absolute widths if you lock the width of the table to a 'total width'. You need the methods setTotalWidth and setLockedWidth for this. In the example the relation between the different cells will remain 10%, 10%, 5%, 75%, so you'll have 2 columns with a width of 30pt, one with a width of 15pt and one that's 225pt wide.

Example: java com.lowagie.examples.objects.tables.CellWidths
Changing the widths of columns: see CellWidths.pdf
If you don't change the defaults, all tables will be glued to eachother or to the other content of the page unless you add the necessary newlines. If you want to avoid this, you can also use the methods setSpacingBefore and setSpacingAfter
Example: java com.lowagie.examples.objects.tables.TableSpacing
Defining the spacing between the table and other content: see TableSpacing.pdf
Go to top of the page
Adding PdfPCells:
The easiest way to add a new cell to a table is using the method addCell(String text). In our first example 'MyFirstTable', we used the method addCell(PdfPCell cell) because we wanted to set some style attributes for the new PdfPCell. If we use addCell(String text) a new PdfPCell is constructed internally with the string as content and using the layout of the 'default cell'. We can change the style attributes of this default cell with the help of the method getDefaultCell. This also works for addCell(Phrase phrase) which is very similar to addCell(String text).

    table.getDefaultCell().setGrayFill(0.8f);
    table.getDefaultCell().setBorderColor(new Color(255, 0, 0));
    table.getDefaultCell().setColspan(2);

Example: java com.lowagie.examples.objects.tables.DefaultCell
Using getDefaultCell to change the default style: see DefaultCell.pdf
Nested Tables
In previous examples we already used setColspan to change the colspan of a Cell. Unfortunately, due to the design of PdfPTable, setRowspan is not supported. You have to use a workaround. Instead of spanning a cell over different rows, you will have to use nested tables for the other cells. You can use addCell(PdfPTable table) to achieve this:
Example: java com.lowagie.examples.objects.tables.NestedTables
Using nested tables: see NestedTables.pdf
Images in a PdfPCell
Finally, there is one 'addCell' method left in PdfPTable: addCell(Image image). You can use this to add an Image that will be scaled to fit in the Cell. This is similar to adding a cell that was constructed with PdfPCell(Image image) or setColspanPdfPCell(Image image, boolean fit), buy as you can see in the example, there are some small differences:
Example: java com.lowagie.examples.objects.tables.ImageCell
Adding an Image to a table: see ImageCell.pdf
External resources for this example: otsoe.jpg
Go to top of the page
Cellheights, -alignment, -padding, -leading, -colors:
The content of a cell is wrapped by default. You can change this default with setNoWrap(true), but the result can look rather ugly, so be carefull with this option.
If you are using the default (nowrap = false), the height of the Cell is adjusted dynamically. Each cell in the same row has the height of the 'highest' cell. iText calculates this height based on different parameters: the number of lines of the content, the leading, the padding,... In some cases you don't want to give that kind of control to iText: you want a cell to have a fixed height. This can be done with the method setFixedHeight. Of course, if the content doesn't fit into this height, you will loose part of it.
Maybe you want to do the opposite: maybe you want a cell to have a minimum height, even if it hasn't that much content. In that case, you'll have to use setMinimumHeight.
Finally, there is another useful method setExtendLastRow. It extends the last row of a Table to the bottom of the page.
Example: java com.lowagie.examples.objects.tables.CellHeights
Playing with heights of PdfPCells: see CellHeights.pdf
The following example demonstrates the self explaining methods setHorizontalAlignment and setVerticalAlignment. For the horizontal alignment, you can choose:

- Element.ALIGN_LEFT
- Element.ALIGN_CENTER
- Element.ALIGN_RIGHT
- Element.ALIGN_JUSTIFIED

For the horizontal alignment:

- Element.ALIGN_TOP
- Element.ALIGN_MIDDLE
- Element.ALIGN_BOTTOM
- Element.ALIGN_BASELINE

Example: java com.lowagie.examples.objects.tables.CellAlignment
Changing the alignment of the contents of a PdfPCell: see Alignment.pdf
The padding is the space between the content and the outer cellborder. You can set the amount of this space with setPadding, setPaddingTop, setPaddingRight, setPaddingLeft and/or setPaddingBottom.
The leading is the space between the lines of the content. This value can be set with setLeading(float,%20float).
Example: java com.lowagie.examples.objects.tables.CellPaddingLeading
Changing the padding and the leading of the contents of a PdfPCell: see PaddingLeading.pdf
If you set the padding, the borderwidth isn't taken into account. You can force iText to calculate the borderwidth into the padding with setUseBorderPadding(true). In the next example, some method to set colors and grayfill of borders and cells are demonstrated. As you can see, the padding of the green cell doesn't take the width of the magenta border into account. In the blue cell, the word 'blue' doesn't overlap with the cyan border. All methods that were used to change the borders and their color, were methods of the class Rectangle.
Example: java com.lowagie.examples.objects.tables.CellColors
Using some Rectangle methods on PdfPCell: see CellColors.pdf
A last set of methods that influence the position of the content within a cell, are the methods setUseAscender and setUseDescender. An example is the best way to demonstrate the difference:
Example: java com.lowagie.examples.objects.tables.TableBorders
Demonstrates different borderstyles: see TableBorders.pdf
In the example shown above, you also learn how to change the width and the color of cellborders.
Go to top of the page
Splitting tables over several pages:
If you have really large tables, you can't expect them to fit on one page. iText splits the table automatically between rows. If your table has a header that needs to be repeated on every page, you need to tell the table how many rows the header counts. This can be done with the method setHeaderRows. In the example, there is one headerrow:
Example: java com.lowagie.examples.objects.tables.AddBigTable
A very big table added with document.add(): see AddBigTable.pdf
In the previous example every row just took one line. If you have rows that are much larger, you must know that tables are split between rows by default. So if only part of a row fits on the current page, the complete row is passed to the next page (see SplitRowsBetween.pdf). Only if the row doesn't fit on 1 page it is split in two.
You can change this by using setSplitLate(false). In this case, the row is split immediately. As you can see in SplitRowsWithin.pdf the maximum size of each page is used.
If you really don't want the rows to be split, you'll have to use setSplitRows(false), but in that case, you will lose a lot of data: see OmitRows.pdf.
Example: java com.lowagie.examples.objects.tables.SplitRows
Add a table to a PDF with document.add() and if the cell doesn't fit, the row is split in two parts: see SplitRowsBetween.pdf SplitRowsWithin.pdf OmitRows.pdf
Go to top of the page
To be continued:
On this page, we have already seen a lot of functionality that makes PdfPTable a flexible and very useful object. But if you really need powerful table functionality, with hundreds of columns and/or thousands and thousands of rows, you need to continue reading about PdfPTable in the next chapter.
Go to top of the page
Amazon books:
amazon.co.uk-link