2016-11-29 70 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事件設置爲零。