テキストファイル印刷

Imports System.IO
Imports System.Text

Public Class Form2

Private Const ERROR_MESSAGE1 = "パス名を指定してください。"

Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

' プレビューダイアログのサイズを大きくする。
PrintPreviewDialog1.Size = New Size(640, 800)

End Sub

Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click

If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
txtPath.Text = OpenFileDialog1.FileName
End If

End Sub

 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

' テキストファイルのパスが設定されているかチェックする。
ErrorProvider1.Clear()
If String.IsNullOrEmpty(txtPath.Text) Then
ErrorProvider1.SetError(txtPath, ERROR_MESSAGE1)
Return
End If

' プレビューを表示する。
PrintPreviewDialog1.ShowDialog()

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

' テキストファイルのパスが設定されているかチェックする。
ErrorProvider1.Clear()
If String.IsNullOrEmpty(txtPath.Text) Then
ErrorProvider1.SetError(txtPath, ERROR_MESSAGE1)

Return
End If
' 印刷開始
Try
PrintDocument1.DocumentName = New FileInfo(txtPath.Text).Name
PrintDocument1.Print()
Catch ex As Exception
MessageBox.Show(ex.Message, "致命的エラー")
End Try

End Sub

 

''' 印刷イベントハンドラ
''' <remarks>印刷行数は1ページに収まる長さでなければならない。</remarks>
Private Sub PrintDocument(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
Dim g As Graphics = e.Graphics
Dim line As String
Dim font As Font = New Font("メイリオ", 11.0)
Dim brush As Brush = New SolidBrush(Color.Black)
Dim x, y As Single

' 行の印刷位置の初期値
x = 20.0F
y = 20.0F
' テキストファイルを1行づつ印刷する。
Using reader = New IO.StreamReader(txtPath.Text, System.Text.Encoding.Default)
' ファイルの終わりまで繰り返す。
While Not reader.EndOfStream
line = reader.ReadLine()
g.DrawString(line, font, brush, x, y)
y += 20.0F
End While
End Using
End Sub


End Class