问题
I'm using ItextSharp to create a PDF document with multiple PdfPTables. I group multiple PdfPTables using a list, and the list is created in a function and returned as a list. I then take the list and loop through it to add each PdfPTable to the document.
In the case that the next PdfPTable in the list is larger than the remaining space on the document I want to add a new page.
Using a breakpoint, I've noticed that "table.TotalHeight" always returns 0, when I expect it to return a positive float value. I might be misunderstanding the way table.TotalHeight works, but to my understanding it should return the total height of the individual table.
for (count1 = 0; count1 < testQuote.Count + 1; count1++)
{
var list = BuildDetail(testQuote, count1);
foreach (PdfPTable table in list)
{
if (table.TotalHeight > (writer.GetVerticalPosition(false) - doc.BottomMargin))
{
doc.Add(new Paragraph("Quote continues on next page"));
doc.NewPage();
}
doc.Add(new Paragraph(" "));
doc.Add(table);
}
回答1:
Unless you are using absolute values the height of a table cannot be known until you render it. Although frustrating at first, it starts to make sense once you start thinking about it. Also, tables can be nested within other things which is why you also need to use fixed widths instead of relative ones.
Knowing that you can use the helper method from this post to calculate the height of a table assuming you've previously fixed the table's column's widths. This code creates a quick temporary in-memory document, renders the table to it and then returns the table's rendered height.
public static float CalculatePdfPTableHeight(PdfPTable table)
{
using (MemoryStream ms = new MemoryStream())
{
using (Document doc = new Document(PageSize.TABLOID))
{
using (PdfWriter w = PdfWriter.GetInstance(doc, ms))
{
doc.Open();
table.WriteSelectedRows(0, table.Rows.Count, 0, 0, w.DirectContent);
doc.Close();
return table.TotalHeight;
}
}
}
}
回答2:
i could get height of table without adding in document, if wrap the table in the cell, then you can use GetMaxHeight()
foreach (PdfPTable table in list)
{
var tableHeight = new PdfPCell(table).GetMaxHeight();
}
来源:https://stackoverflow.com/questions/33134927/using-itextsharp-pdfptable-table-totalheight-returns-0-0-but-expecting-a-posit