16,554
社区成员
发帖
与我相关
我的任务
分享
Imports System.Drawing
Imports System.IO
Imports System.Windows.Forms
Public Class Form1
Dim StrToPage As String
Dim StreamToPrint As StreamReader
Dim FileToPrint As String = "C:\PrintTest.txt"
Private Sub ReadFile()
StreamToPrint = New StreamReader(FileToPrint, System.Text.Encoding.GetEncoding("utf-8"))
End Sub
Private Sub CloseFile()
StreamToPrint.Close()
StreamToPrint.Dispose()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.PageSetupDialog1.Document = PrintDocument1
Me.PrintPreviewDialog1.Document = PrintDocument1
Me.PrintDialog1.Document = PrintDocument1
End Sub
Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
Dim linesPerPage As Single = 0
Dim linesCount As Integer = 0
Dim yPosition As Integer = 0
Dim lineStr As String = Nothing
Dim printfont As New Font("宋体", 12, FontStyle.Regular, GraphicsUnit.Pixel)
Dim fontHeight = printfont.GetHeight
linesPerPage = e.MarginBounds.Height / FontHeight
While (linesCount < linesPerPage)
lineStr = StreamToPrint.ReadLine()
If lineStr Is Nothing Then Exit While
yPosition = e.MarginBounds.Top + linesCount * fontHeight
e.Graphics.DrawString(lineStr, printfont, Brushes.Black, e.MarginBounds.Left, yPosition)
linesCount += 1
End While
If lineStr IsNot Nothing Then
e.HasMorePages = True
Else
e.HasMorePages = False
End If
End Sub
'打印预览
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ReadFile()
Try
Me.PrintPreviewDialog1.ShowDialog()
Catch ex As Exception
CloseFile()
End Try
End Sub
'页面设置
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.PageSetupDialog1.ShowDialog()
End Sub
'打印
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
ReadFile()
Try
Dim res As DialogResult = Me.PrintDialog1.ShowDialog()
If res = DialogResult.OK Then
PrintDocument1.Print()
End If
Catch ex As Exception
CloseFile()
End Try
End Sub
End Class