Add a PDFPTable to bottom of page in iText

2020-07-18 05:53发布

I'm trying to add a table as a footer containing all the copyright text, page number etc. But I can't find any supporting method that'll accept a PdfPTable

For a phrase there is code like:

ColumnText.showTextAligned(writer.getDirectContent(),
        Element.ALIGN_CENTER, new Phrase(
            String.format("%d", document.getPageNumber())),
            (document.getPageSize().getLeft() + document.getPageSize().getRight())/2,
            document.getPageSize().getBottom() + 18, 0);

标签: java itext
3条回答
Rolldiameter
2楼-- · 2020-07-18 06:13

The examples posted by Bruno are a good pointer, here's an example without magic numbers:

    private void writeFooterTable(PdfWriter writer, Document document, PdfPTable table) {
        final int FIRST_ROW = 0;
        final int LAST_ROW = -1;
        //Table must have absolute width set.
        if(table.getTotalWidth()==0)
            table.setTotalWidth((document.right()-document.left())*table.getWidthPercentage()/100f);
        table.writeSelectedRows(FIRST_ROW, LAST_ROW, document.left(), document.bottom()+table.getTotalHeight(),writer.getDirectContent());
    }

This will write the PdfPTable within the document margins at the bottom overlapping any text you have at the bottom. If you wish to write the table in the margin, use: document.bottom() instead of document.bottom()+table.getTotalHeight().


Header/Footer Example

As a relevant note if you're following the example on this link, the "art" box does not appear to be required and the magic numbers 36, 54, 559, 788 correspond to:

document.left(), document.bottom(), document.right(), document.top()
查看更多
3楼-- · 2020-07-18 06:35

The PdfPTable class has a method writeSelectedRows() that can be used to add (a selection of columns and) rows at an absolute position.

Examples:

查看更多
Root(大扎)
4楼-- · 2020-07-18 06:37

To implement a custom footer you need to implement the PdfPageEventHelper.

查看更多
登录 后发表回答