Add a PDFPTable to bottom of page in iText

自闭症网瘾萝莉.ら 提交于 2020-01-01 12:01:12

问题


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);

回答1:


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

Examples:

  • http://itextpdf.com/examples/iia.php?id=89 adds rows at an absolute position.
  • http://itextpdf.com/examples/iia.php?id=90 adds a selection of columns/rows at an absolute position.
  • http://itextpdf.com/examples/iia.php?id=91 an alternative solution where you wrap a table in a ColumnText object.



回答2:


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:


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



来源:https://stackoverflow.com/questions/12796525/add-a-pdfptable-to-bottom-of-page-in-itext

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!