【问题标题】:How to get the height of itextSharp table cell in C#?如何在 C# 中获取 itextSharp 表格单元格的高度?
【发布时间】:2016-06-20 15:56:02
【问题描述】:

我想得到以下单元格的高度。

cell_logo

单元格标题

cell_version

cell_dateTime

cell_appVersion

cell_name.Height 返回 0 。如何获得这些单元格的实际高度?

PdfPTable table = new PdfPTable(1);
        table.TotalWidth = doc.PageSize.Width - doc.LeftMargin - doc.RightMargin;            
        table.LockedWidth = true;        

        PdfPCell cell_logo = new PdfPCell(imgLog);
        cell_logo.HorizontalAlignment = 1;
        cell_logo.BackgroundColor = new BaseColor(System.Drawing.Color.White);
        cell_logo.PaddingBottom = 20;
        cell_logo.PaddingTop = 50;

        PdfPCell cell_title = new PdfPCell(docName);
        cell_title.HorizontalAlignment = 1;
        cell_title.BackgroundColor = new BaseColor(System.Drawing.Color.White);
        cell_title.PaddingBottom = 50;

        PdfPCell cell_versions = new PdfPCell(ssVersions);
        cell_versions.BackgroundColor = new BaseColor(System.Drawing.Color.White);            
        cell_versions.PaddingTop = 5;
        cell_versions.PaddingBottom = 5;

        PdfPCell cell_dateTime = new PdfPCell(time);
        cell_dateTime.BackgroundColor = new BaseColor(System.Drawing.Color.White);
        cell_dateTime.PaddingTop = 5;
        cell_dateTime.PaddingBottom = 5;

        PdfPCell cell_appVersion =  new PdfPCell(SSCGVersion);
        cell_appVersion.BackgroundColor = new BaseColor(System.Drawing.Color.White);
        cell_appVersion.MinimumHeight = doc.PageSize.Height - doc.TopMargin - doc.BottomMargin - cell_logo.Height - cell_title.Height - cell_versions.Height - cell_dateTime.Height;


        table.AddCell(cell_logo);
        table.AddCell(cell_title);
        table.AddCell(cell_versions);
        table.AddCell(cell_dateTime);
        table.AddCell(cell_appVersion);          

        doc.Add(table); 

其实我想设置表格高度等于页面大小

【问题讨论】:

标签: c# pdf height itextsharp cell


【解决方案1】:

阅读您的代码示例,我注意到您已阅读此问题的答案:Itextsharp: Adjust 2 elements on exactly one page

您正确设置了表格的宽度,如果您要计算高度,这是强制性的:

table.TotalWidth = doc.PageSize.Width - doc.LeftMargin - doc.RightMargin;            
table.LockedWidth = true; 

您现在想知道每个单元格的高度。这对你不起作用,因为你看错了地方。你不应该看单元格的高度,你应该看单元格所属行的高度。单元格的高度并不重要,重要的是行的高度。

这在iTextSharp: How to find the first and second row height in a table?问题的答案中有解释

float h1 = table.GetRowHeight(0);
float h2 = table.GetRowHeight(1);

您的最终目标是设置表格的高度,使其适合页面。如果可以通过扩展最后一行来完成,那么您可以使用问题的答案Itextsharp make footer stick at bottom of every pdf page

table.SetExtendLastRow(true, true);

如果这不可接受,并且您想单独定义每行的高度,那么您的任务就会更加困难。在这种情况下,您需要阅读此问题的答案Setting height for table in iTextSharp

我将您的问题标记为可能重复,但随后我重新考虑并决定发布答案,因为您的问题的答案实际上可能不是完全重复的,但可能需要结合已经给出的答案.

【讨论】:

  • 很好 - 考虑到几个不同场景的一个答案。