Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.3k views
in Technique[技术] by (71.8m points)

vb.net - Printing multiple pages using PrintDocument and HasMorePages

I'm trying to print a list of items in a listbox. I have 284 items. About a quarter of them get printed and the rest don't print and at the bottom the last entry is half way cutoff. I read online about keeping track of where you left off and printing to the next page by utilizing e.HasMorePages but nothing prints now and it just says its print page 1,2,3,4,5....etc. and nothing happens. I have to ctrl+c it and close program. How can I achieve desired print out?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
...