计算将从DataGridView打印的总页数

本文关键字:打印 DataGridView 计算 | 更新日期: 2023-09-27 18:29:59

我正在尝试计算将从DataGridView打印的页面总数。一旦总列长度大于总打印面积,将打印新页面。对于每个新页面,它将始终打印列0,因此需要添加列宽以获得正确的计算。

这是我到目前为止所拥有的,似乎总是缺少页码

//dgv = the DataGridView
//RectangleF printable_area = MarginBounds
float total_width = 0;
//grab the width of each column
for (int i = 0; i < dgv.ColumnCount; i++)
{
    total_width += dgv.Columns[i].HeaderCell.Size.Width;
}
//divide the total width by the printable area's width
int pages = (int)Math.Ceiling(total_width / (printable_area.Size.Width));
//add to the total width the size of column 0 * the number of pages
total_width += dgv.Rows[0].Cells[0].Size.Width * pages;
//return the total number of pages that will be printed
return (int)Math.Ceiling(total_width / (printable_area.Size.Width));

计算将从DataGridView打印的总页数

一开始我以为你实际上会有更多的页面,因为你在计算中包括了两次第一页的Column[0](在我看来,变量i应该从1开始),但后来我意识到这个计算

int pages = (int)Math.Ceiling(total_width / (printable_area.Size.Width));

将假定列可以分布在页面上。

假设您有4列,每列的大小为100宽。现在假设您的可打印区域宽度为150。忽略每页打印第一列的要求,这将给你3页,因为400/150是2.67,四舍五入到3。然而,您实际想要的是4页,因为两列永远不能放在一页上,而且每页宽度为50的额外"间隙"是不可用的。

这是假设您不想在每页上打印半个或部分列。如果这是您的意图,那么我看不出您的代码有任何进一步的错误