以编程方式在vb.net中插入分页符

时间:2012-07-26 13:44:02

标签: vb.net printing formatting

所以我试图在从我的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。

1 个答案:

答案 0 :(得分: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

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