2

所以我试图在直接从我的 VB.NET 程序打印时强制分页。我基本上是使用 MSDN 中的这段代码来打印我的文档:

Private Sub printDocument1_PrintPage(ByVal sender As Object, _
    ByVal e As PrintPageEventArgs)

    Dim charactersOnPage As Integer = 0
    Dim linesPerPage As Integer = 0

    ' Sets the value of charactersOnPage to the number of characters 
    ' of stringToPrint that will fit within the bounds of the page.
    e.Graphics.MeasureString(stringToPrint, Me.Font, e.MarginBounds.Size, _
        StringFormat.GenericTypographic, charactersOnPage, linesPerPage)

    ' Draws the string within the bounds of the page
    e.Graphics.DrawString(stringToPrint, Me.Font, Brushes.Black, _
    e.MarginBounds, StringFormat.GenericTypographic)

   ' Remove the portion of the string that has been printed.
    stringToPrint = stringToPrint.Substring(charactersOnPage)

    ' Check to see if more pages are to be printed.
    e.HasMorePages = stringToPrint.Length > 0

End Sub

这使它可以很好地打印,但我想在特定位置放置分页符。我试过 e.HasMorePages = true,但我不明白这如何让我在特定位置中断。假设我的 stringToPrint 长度为 5000 个字符,我想在 1000 个字符后开始新页面,然后在接下来的 2500 个字符后重新开始。我该怎么做?

此外,将linesOnPage 和charactersOnPage 更改为其他值似乎根本没有改变任何东西。

编辑:我想关于我的程序所做的更多信息会有所帮助。基本上它所做的是程序将创建大约 4 个完整的数据页,并将其打印到 .txt 文件中。现在,我想打印整个 .txt 文件。我知道如何做到这一点的唯一方法是打印一个字符串,所以我让它逐行读取整个 .txt 文件并将其全部存储为一个字符串(即 stringToPrint)。现在,使用上面的代码,我打印 stringToPrint。

4

1 回答 1

0

您当前的代码基于打印到矩形:e.MarginBounds

为了测试,我使用了这段代码:

Private pageNum As Integer

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
                          Handles Button1.Click
  Dim sb As New StringBuilder
  For i As Integer = 1 To 100
    sb.AppendLine(i.ToString & ") This is a line.")
  Next
  stringToPrint = sb.ToString

  pageNum = 0
  Using pvw As New PrintPreviewDialog()
    pvw.Document = printDocument1
    pvw.ShowDialog()
  End Using
End Sub

然后我改变了你的例程,在第一页上使用了一个较小的矩形:

Private Sub printDocument1_PrintPage(ByVal sender As Object, _
                                     ByVal e As PrintPageEventArgs) _
                                     Handles printDocument1.PrintPage
  Dim charactersOnPage As Integer = 0
  Dim linesPerPage As Integer = 0

  pageNum += 1

  Dim printSize As Size = e.MarginBounds.Size
  If pageNum = 1 Then
    printSize = New Size(printSize.Width, printSize.Height / 2)
  End If
  e.Graphics.MeasureString(stringToPrint, Me.Font, printSize, _
      StringFormat.GenericTypographic, charactersOnPage, linesPerPage)

  ' Draws the string within the bounds of the page
  e.Graphics.DrawString(stringToPrint, Me.Font, Brushes.Black, _
    New Rectangle(e.MarginBounds.Location, printSize), _
    StringFormat.GenericTypographic)

  ' Remove the portion of the string that has been printed.
  stringToPrint = stringToPrint.Substring(charactersOnPage)

  ' Check to see if more pages are to be printed.
  e.HasMorePages = stringToPrint.Length > 0
End Sub

如果您需要根据字符控制打印,则必须放弃打印文本块的代码并逐行打印所有内容。

于 2012-07-26T14:52:42.287 回答