使用PrintDocument和HasMorePages打印多个页面

时间:2016-11-29 18:17:07

标签: vb.net winforms printdocument

我正在尝试打印列表框中的项目列表。我有284项。其中约四分之一被打印,其余部分不打印,最后一个条目是中途截止。我在网上看到了关于你离开的地方并通过利用e.HasMorePages打印到下一页但现在没有打印它只是说它的打印页1,2,3,4,5 ....等。没有任何反应。我必须按ctrl + c然后关闭程序。如何实现所需的打印输出?

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

1 个答案:

答案 0 :(得分:4)

您编写代码的方式告诉我您认为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

在打印前将printLine变量设置为零,或在BeginPrint事件中将其设置为零。