Printing multiple pages using PrintDocument and HasMorePages

The way you wrote your code tells me you think the PrintPage method is only getting called once, and that you are using that one call to print everything. That’s not the way it works.

When a new page needs to be printed, it will call the PrintPage method again, so your loop variable has to be outside the PrintPage scope. When the next page prints, you need to know what line number you are currently printing.

Try it like this:

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

Set the printLine variable to zero before you print, or set it to zero in the BeginPrint event.

Leave a Comment