2016-11-29 71 views
2

我试图打印列表框中的项目列表。我有284项。其中大约四分之一被打印,其余不打印,底部最后一个入口被截断。我在网上阅读了关于通过利用e.HasMorePages跟踪您从哪里停止并打印到下一页的内容,但现在没有任何打印内容,它只是说它的打印页面1,2,3,4,5 ....等等。没有任何反应。我必须按ctrl + c并关闭程序。我怎样才能达到理想的打印效果?使用PrintDocument和HasMorePages打印多个页面

Private Sub Print_Click(sender As Object, e As EventArgs) Handles Print.Click 
    Dim PrintDialog1 As New PrintDialog 
    Dim result As DialogResult = PrintDialog1.ShowDialog() 
    If result = DialogResult.OK Then PrintDocument1.Print() 

    ' PrintPreviewDialog1.Document = PrintDocument1 
    ' PrintPreviewDialog1.ShowDialog() 
End Sub 

Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage 
    ' e.HasMorePages = True 
    Dim itemCount As Integer 
    Dim startX As Integer = 10 
    Dim startY As Integer = 10 
    Dim n As Integer 
    For x As Integer = 0 To SoftwareLBox.Items.Count - 1 
    e.Graphics.DrawString(SoftwareLBox.Items(x).ToString, SoftwareLBox.Font, Brushes.Black, startX, startY) 
    startY += SoftwareLBox.ItemHeight 
    If n = 150 Then 
     e.HasMorePages = True 
     n = 0 
     startY = 10 
    End If 
    startY += e.PageBounds.Height 
    n += 1 
    Next 
End Sub 

回答

3

您编写代码的方式告诉我您认为PrintPage方法只会被调用一次,并且您正在使用该调用来打印所有内容。这不是它的工作方式。

当一个新页需要打印,它将再次调用的PrintPage方法,让你的循环变量是的PrintPage范围之外。当下一页打印时,您需要知道当前正在打印的行号。

试试这样说:

Private printLine As Integer = 0 

Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) 
    Dim startX As Integer = e.MarginBounds.Left 
    Dim startY As Integer = e.MarginBounds.Top 
    Do While printLine < SoftwareLBox.Items.Count 
    If startY + SoftwareLBox.ItemHeight > e.MarginBounds.Bottom Then 
     e.HasMorePages = True 
     Exit Do 
    End If 
    e.Graphics.DrawString(SoftwareLBox.Items(printLine).ToString, SoftwareLBox.Font, _ 
          Brushes.Black, startX, startY) 
    startY += SoftwareLBox.ItemHeight 
    printLine += 1 
    Loop 
End Sub 

设置打印线变到零在打印之前,或者在BeginPrint事件设置为零。