iText java - 垂直和水平拆分 table

iText java - Split table vertically and horizontally

我是一名 iText java 开发人员。我一直在使用大型 tables,现在我被困在垂直拆分 table 中。

在 iText in Action 的第 119 页,尊敬的 Bruno Lowagie(我非常尊重这个人)解释了如何拆分一个大 table 以便列出现在两个不同的页面中。

我按照他的例子做了,当文档只有几行时效果很好。

在我的例子中,我有 100 行,说明文档需要将 100 行拆分为多个页面,同时垂直拆分列。我 运行 我的代码如下,但只显示前 34 行。

谁能解释一下这段代码可能有什么问题:

//create a PDFPTable with 24 columns
PdfPTable tbl = new PdfPTable(new float{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1});
//loop through 100 rows
for (int i = 0; i < 100; i++) {
    //insert 24 table cells
}

tbl.setTotalWidth(1500);//set table width
float top = document.top() - document.topMargin() - 30;
PdfContentByte canvas = writer.getDirectContent();
tbl.writeSelectedRows(0, 12, 0, -1, document.leftMargin(), top, canvas);
document.newPage();
// draw the remaining two columns on the next page
tbl.writeSelectedRows(12, -1, 0, -1, 5, top, canvas);

您看不到 100 行,因为 100 行放不下一个页面。使用writeSelectedRows()时,需要计算页面适合的行数,只添加适合的行选择。

我目前正在柏林参加一个会议,但我写了一个简单的示例,或多或少地显示了您需要做的事情:

public void createPdf(String dest) throws IOException, DocumentException {
    Document document = new Document(PageSize.A4.rotate());
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
    PdfPTable tbl = new PdfPTable(new float[]{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1});
    //loop through 100 rows
    for (int r = 1; r <= 100; r++) {
        for (int c = 1; c <= 24; c++) {
            tbl.addCell(String.format("r%sc%s", r, c));
        }
    }
    PdfContentByte canvas = writer.getDirectContent();
    tbl.setTotalWidth(1500);//set table width
    float top = document.top() - document.topMargin() - 30;
    float yPos = top;
    int start = 0;
    int stop = 0;
    for (int i = 0; i < 100; i++) {
        yPos -= tbl.getRowHeight(i);
        if (yPos < 0) {
            stop = --i;
            tbl.writeSelectedRows(0, 12, start, stop, document.leftMargin(), top, canvas);
            document.newPage();
            tbl.writeSelectedRows(12, -1, start, stop, 5, top, canvas);
            start = stop;
            document.newPage();
            yPos = top;
        }
    }
    tbl.writeSelectedRows(0, 12, stop, -1, document.leftMargin(), top, canvas);
    document.newPage();
    tbl.writeSelectedRows(12, -1, stop, -1, 5, top, canvas);
    document.close();
}

如您所见,我会跟踪 table 的高度,一旦它有 "falling off the page" 的风险,我就会渲染适合的行,然后转到下一页。