How to create a table with 2 rows that can be used as a footer?

Category: 
Tags: page eventstablesheaderfooterposition tableiText 7

I want to add footer with 2 rows. The 1st row will have the document name with a background color. The 2nd row will have copyright notices. I tried to create this table using ColumnText, but I am not able to set the background color for the row (only the text is getting background color).

Posted on StackOverflow on Mar 2, 2014 by Satesh S

You can set the background of a cell using the setBackgroundColor() method.

Take a look at the TableFooter example:

Table table = new Table(1);
table.setWidth(523);
Cell cell = new Cell().add(new Paragraph("This is a test doc"));
cell.setBackgroundColor(Color.ORANGE);
table.addCell(cell);
cell = new Cell().add(new Paragraph("This is a copyright notice"));
cell.setBackgroundColor(Color.LIGHT_GRAY);
table.addCell(cell);

Then if you are using iText 7 you should write the implementation of IEventHandler and add this table to the document using Canvas instance:

protected class TableFooterEventHandler implements IEventHandler {
    private Table table;
 
    public TableFooterEventHandler(Table table) {
        this.table = table;
    }
    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdfDoc = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        PdfCanvas canvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDoc);
        new Canvas(canvas, pdfDoc, new Rectangle(36, 20, page.getPageSize().getWidth() - 72, 50))
                .add(table);
    }
}

Here it is! Make sure you define the margins of your page in such a way that the footer table doesn't overlap with the page content.

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