VB.NET•Generate the Printed and Preview Output

Listing 2. The PrintPage event of the PrintDocument class (or its derivative in this case) is where the user of the print preview form does the actual printing.

Private Sub TestByControl_Click(...)
   ' ----- Display a sample document.
   Dim previewForm As PrintingTest.ControlMethod
   Dim timeToPrint As DialogResult

   PageSoFar = 0
   BarcodeDoc = New PrintingTest.DocumentWithTOC
   previewForm = New ControlMethod
   previewForm.Document = BarcodeDoc
   timeToPrint = previewForm.ShowDialog()
End Sub

Private Sub BarcodeDoc_PrintPage(...)
   ' ----- Print one page of the document.
   Dim theDocument As PrintingTest. _
      DocumentWithTOC
   Dim thisGroup As String
   Static lastGroup As String = ""

   ' ----- Each page displays the state name.
   e.Graphics.DrawString(StateArray(PageSoFar), _
      (New Font("Arial", 36)), _
      Brushes.Black, 100, 100)
   thisGroup = UCase(Microsoft.VisualBasic. _
      Left(StateArray(PageSoFar), 1))
   PageSoFar += 1

   ' ----- Add one TOC entry for the state,
   ' ----- and optionally one for the first
   ' ----- letter of the state name.
   theDocument = CType(sender, PrintingTest. _
      DocumentWithTOC)
   If (thisGroup <> lastGroup) Then _
      theDocument.AddTOCEntry("'" & _
      thisGroup & "' States", 1, PageSoFar)
   lastGroup = thisGroup
   theDocument.AddTOCEntry(StateArray( _
      PageSoFar - 1), 2, PageSoFar)

   ' ----- See if we have reached the last page.
   If (PageSoFar > StateArray.GetUpperBound(0)) _
      Then e.HasMorePages = False _
      Else e.HasMorePages = True
End Sub