1

PdfPTable#getTotalHeight()方法在写入文档之前返回 0。有没有办法在写入文档之前获得高度?

Document document = new Document();
PdfWriter instance = PdfWriter.getInstance(document, new FileOutputStream("output.pdf"));
document.open();

PdfPTable table = ...

System.out.println("table total height: " + table.getTotalHeight());
document.add(table);
System.out.println("after adding to doc");
System.out.println("table total height: " + table.getTotalHeight());

document.close();

控制台输出:

table total height: 0.0
after adding to doc
table total height: 1249.3105
4

1 回答 1

0

问题是没有宽度,就无法计算表格的高度。当我们将表格添加到文档中时,宽度将根据页面大小、边距和表格的相对关系来计算(默认设置为 80%)。

我们可以使用 手动为表格分配固定宽度table.setTotalWidth(...)。之后高度立即可用。如果我们想将定义为固定的表格添加到文档中,我们需要用 锁定它table.setLockedWidth(true)。您手动设置的宽度取决于您要添加表格的确切位置。您需要自己预先计算容器的宽度。

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("output.pdf"));
document.open();

// add a table with 2 columns and 3 rows and some filler text (LOREM_IPSUM)
PdfPTable table = new PdfPTable(2);
table.addCell(LOREM_IPSUM); table.addCell(LOREM_IPSUM);
PdfPCell cell = new PdfPCell(new Paragraph(LOREM_IPSUM));
cell.setColspan(2); table.addCell(cell);
table.addCell(LOREM_IPSUM); table.addCell(LOREM_IPSUM);

// manually set the width (as an example to page content width)
float containerWidth = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin();
table.setTotalWidth(containerWidth);
table.setLockedWidth(true);

// get height of table before and after adding it to the document
System.out.println("Height before adding: " + table.getTotalHeight());
document.add(table);
System.out.println("Height after adding:  " + table.getTotalHeight());

document.close();
Height before adding: 132.0
Height after adding:  132.0
于 2021-07-18T09:45:11.200 回答