Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iText Document Vertical Alignment

I'm trying to vertically align a table in my document to the bottom of the page.

I've set the vertical alignment of the table to BOTTOM but that just makes the cells align to the bottom of the table itself.

How can I make the Document itself vertically aligned to the bottom?

Thanks

like image 773
Shaun Avatar asked Sep 27 '11 12:09

Shaun


1 Answers

After many days of searching.. my solution was to wrap my table in an outer table with 1 cell. Set the cell to the height of the page minus the two margins and set vertical alignment to the bottom. Add all content you want bottom justified to this table.

Full example, error code omitted for brevity

public void run() {
    try {
        Document document = new Document(PageSize.LETTER, 10.0f, 10.0f, 36.0f, 36.0f);
        PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("test.pdf"));
        document.open();

        PdfPTable outerTable = new PdfPTable(1);
        outerTable.setWidthPercentage(100.0f);

        PdfPCell cell = new PdfPCell();
        cell.setMinimumHeight(document.getPageSize().getHeight() - 36.0f - 36.0f);
        cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cell.addElement(createTable());

        outerTable.addCell(cell);
        document.add(outerTable);
        document.newPage();
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

public PdfPTable leftTable() {
    PdfPTable table = new PdfPTable(1);
    for (int i = 0; i < 50; i++) {
        table.addCell("Cell: " + i);
    }
    return table;
}

public PdfPTable middleTable() {
    PdfPTable table = new PdfPTable(1);
    for (int i = 0; i < 10; i++) {
        table.addCell("Cell: " + i);
    }
    return table;
}

public PdfPTable rightTable() {
    PdfPTable table = new PdfPTable(1);
    for (int i = 0; i < 100; i++) {
        table.addCell("Cell: " + i);
    }
    return table;
}

public PdfPTable createTable() {
    PdfPTable table = new PdfPTable(3);

    table.getDefaultCell().setVerticalAlignment(Element.ALIGN_BOTTOM);
    table.addCell(leftTable());
    table.addCell(middleTable());
    table.addCell(rightTable());

    return table;
}
like image 70
Shaun Avatar answered Sep 21 '22 22:09

Shaun