【问题标题】:How to get height of a table without writing to document如何在不写入文档的情况下获得桌子的高度
【发布时间】:2021-09-02 06:48:16
【问题描述】:

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

【问题讨论】:

  • 您需要它是否有特定原因?只需为每个高度检查创建一个新的空文档。
  • @Nexarius 出于性能原因,我想避免写入文档。
  • 你能做一个可编译的可复制示例吗?我实际上已经收到了一个非常相似的任务,并通过谷歌搜索找到了这个问题(因为我实际上认为它会像你描述的那样工作)。但是,就我而言,它实际上是开箱即用的,但现在我担心getTotalHeight 可能会返回零并破坏我的逻辑。
  • @adnan_e 我刚刚回答了这个问题。

标签: java openpdf


【解决方案1】:

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

我们可以使用table.setTotalWidth(...) 手动为表格分配固定宽度。之后高度立即可用。如果我们想将定义了fixed with的表添加到文档中,我们需要用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    相关资源
    最近更新 更多