itext, table 在新页面拆分时宽度变化

Itext, table width changes when splitted in new page

我正在使用 iText 5.3.4Eclipse Kepler。我有一张账单 table,通常不会超过一页,但为了测试目的,我一直在检查它的行为,我遇到了一个奇怪的问题,table width页面更改时更改:

我的table定义:

PdfPTable tableFactura = new PdfPTable(4);
tableFactura.setWidthPercentage(80f);
tableFactura.setWidths(new int[]{55, 15, 15, 15});
tableFactura.setKeepTogether(false);
tableFactura.setHeaderRows(1);

如果我定义不同的宽度,问题仍然存在,但尺寸不同。

table填在一个for-loop里面,里面有PdfCellParagraph,没什么复杂的:

// ONE of the CELLS of each line
cell = new PdfPCell(new Paragraph(factura.get("descripcion_linea" + numeroLinea), tinyNormal));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setPaddingLeft(10f);
cell.setPaddingTop(5f);
cell.setBorder(Rectangle.LEFT);
tableFactura.addCell(cell);

我的文件是标准的,Document document = new Document();,我也试过包括 document.setPageSize(PageSize.A4); 但没有任何改变。正如您在图片中看到的,我也尝试过在单元格中没有内容。

知道为什么会这样吗?

UPDATE1: 根据@Bruno 的建议这里是 Link To File.

UPDATE2: here 是一段代码 "simulating" 我在做什么,但问题是 NOT 正在发生

我从未使用过 iText,但我认为问题出在以下几行。

tableFactura.setWidthPercentage(80f);
tableFactura.setWidths(new int[]{55, 15, 15, 15});

你能试试下面的两种情况,让我知道结果如何吗?

案例 1:设置宽度 100%

tableFactura.setWidthPercentage(100f);
tableFactura.setWidths(new int[]{55, 15, 15, 15});

案例 2:设置宽度为 80%

tableFactura.setWidthPercentage(80f);
tableFactura.setWidths(new int[]{50, 10, 10, 10});

如果没有,检查这个this question可能会有帮助。

好吧,我终于解决了。感谢 @BrunoLowagie and @Fahim Parkar

将根据所有建议快速解释我的所有修改:

首先 根据@Bruno 评论,首先我删除了未使用的方法PdfPTable::setKeepTogether(boolean);

其次,并根据this question, posted by @Fahim (thanks!). We can force table's size by PdfPTable::setLockedWitdth(boolean)before设置TotalWidth.

PdfPTable tableFactura = new PdfPTable(4);
tableFactura.setLockedWidth(true);
tableFactura.setTotalWidth(425f);
tableFactura.setWidths(new int[]{55, 15, 15, 15});

这允许 table 在所有页面中具有相同的大小......但并非全部完成,以避免在最后一行和分页符(单页或多页)中出现奇怪的行为,我必须包括:

tableFactura.setSkipLastFooter(true);

第三: 现在 table 限制是正确的,只需要更正分页符,为此我定义了页脚行。

tableFactura.setHeaderRows(2);
tableFactura.setFooterRows(1);

注意:根据 PdfPTable::setFooterRows():

Sets the number of rows to be used for the footer. The number of footer rows are subtracted from the header rows. So in this example row 1 will be footer and row 2 will be header.

第四: 只需根据我的需要调整边距、边框和填充,我就能得到我想要的准确结果。

TA达! :)