【发布时间】:2016-01-11 20:42:09
【问题描述】:
此代码打印 DataGridView 中的所有行,如果需要,将它们打印在多个页面上。
我确保正确使用 e.HasMorePages,甚至单步执行代码,它在第 1 页末尾正确退出 PrintPage 例程,以便可以打印第 2 页。但是当它完成时,两个页面会相互重叠,而不是在各自的页面上。
代码:
' These are all at the beginning of the class (form)
Private WithEvents printDocument1 As New Printing.PrintDocument
Private ColumnCount As Integer = 0
Private RowCount As Integer = 0
Private CurrRow As Integer = 0
Private CellTopPos As Integer = 0
Private CellLeftPos As Integer = 0
' this is the button on the form that runs the print routine
Private Sub btnPrint_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnPrint.Click
CurrRow = 0
PrintDocument1.Print()
End Sub
Private Sub printDocument1_PrintPage(ByVal sender As Object, _
ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles printDocument1.PrintPage
' start printing current row at top of page
With printDocument1
CellTopPos = .DefaultPageSettings.Margins.Top
While CellTopPos < .DefaultPageSettings.PaperSize.Width - _
.DefaultPageSettings.Margins.Bottom
' start printing current row at left of page
CellLeftPos = .DefaultPageSettings.Margins.Left
For Cell = 0 To ColumnCount - 1
Dim CellValue As String = _
grdSearch.Rows(CurrRow).Cells(Cell).Value.ToString()
Dim CellWidth = _
grdSearch.Rows(CurrRow).Cells(Cell).Size.Width + 50
Dim CellHeight = _
grdSearch.Rows(CurrRow).Cells(Cell).Size.Height
Dim Brush As New SolidBrush(Color.Black)
e.Graphics.DrawString(CellValue, _
New Font("Century Gothic", 10), Brush, CellLeftPos, CellTopPos)
e.Graphics.DrawRectangle(Pens.Black, CellLeftPos, _
CellTopPos, CellWidth, CellHeight)
CellLeftPos += CellWidth
Next
CellTopPos += grdSearch.Rows(CurrRow).Cells(0).Size.Height
CurrRow = CurrRow + 1
If CurrRow = RowCount Then Exit While
End While
End With
If CurrRow < RowCount Then
e.HasMorePages = True
Else
e.HasMorePages = False
End If
End Sub
仓促编辑:ColumnCount 和 RowCount 是在 FormLoad 子中填充 dataGridView 时计算的
【问题讨论】:
-
您的 While 循环不应该使用
.DefaultPageSettings.PaperSize.Top而不是.DefaultPageSettings.PaperSize.Width吗?似乎Width将始终小于Bottom,从而产生负数(我假设以纵向打印的标准 Letter 尺寸的纸张)。如果在我看来您不需要从Top中减去Bottom,只需将CellTopPos与Bottom进行比较即可。 -
题外话,但应该是这样的:
While CellTopPos < .DefaultPageSettings.PaperSize.Height - .DefaultPageSettings.Margins.Bottom1顺便说一句,当我使用grdSearch.RowCount和grdSearch.ColumnCount时它工作正常 -
Chris:确实,不清楚,但我使用的是横向,所以这就是我使用宽度的原因。唉,无论是纵向还是横向,它仍然会运行到下一页,因此是问题所在。至于为什么我使用横向,是因为我知道网格中列的宽度,并且知道它对于纵向来说太大了而且我也不知道如何打印多页,这是令人沮丧的部分.我在另一部分代码中有一个多页打印例程,它工作得很好。它打印在卡片的两侧(如身份证)
标签: vb.net printing printdocument