如何打印文本文件?

How to print text files?

我已经创建并保存了一个 .txt 文件,现在我打算打印它。该文件可能足够大,需要多个页面。这是我的代码:

'Print file
Dim docName As String = name1 & " " & name2 & ".txt"
Dim docPath As String = "Z:\Completed\"
printDocument1.DocumentName = docName
Dim stream As New FileStream(docPath & docName, FileMode.Open)
Try
    Dim reader As New StreamReader(stream)
    Try
        stringToPrint = reader.ReadToEnd()
    Finally
        reader.Dispose()
    End Try
Finally
    stream.Dispose()
End Try
printDocument1.Print()


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

我的问题是每次都打印空白页。单步执行代码,我可以看到 "docName" 和 "docPath" 设置正确。

示例:

docName = 测试 1.txt

docPath = Z:\Completed\

MSDN example 很不清楚(示例代码甚至没有显示),但您必须手动添加 PrintPage 事件处理程序。在声明 printDocument1 之后但在调用 printDocument1.Print() 之前添加此行:

AddHandler printDocument1.PrintPage, AddressOf printDocument1_PrintPage

或者,您可以将 Sub 声明更改为:

Private Sub printDocument1_PrintPage(ByVal sender As Object, _
ByVal e As PrintPageEventArgs) Handles printDocument1.PrintPage

Edit:要使用此方法,您必须使用 WithEvents 关键字声明 printDocument1,如下所示:

Dim WithEvents printDocument1 As ...