001.
using
System;
002.
using
System.IO;
003.
using
System.Drawing;
004.
using
System.Drawing.Printing;
005.
using
System.Windows.Forms;
006.
007.
008.
public
partial
class
Form1 : System.Windows.Forms.Form
009.
{
010.
private
System.ComponentModel.Container components;
011.
private
System.Windows.Forms.Button printButton;
012.
private
Font printFont;
013.
private
StreamReader streamToPrint;
014.
015.
public
Form1()
016.
{
017.
018.
InitializeComponent();
019.
}
020.
021.
022.
private
void
printButton_Click(
object
sender, EventArgs e)
023.
{
024.
try
025.
{
026.
streamToPrint =
new
StreamReader
027.
(
"C:\\My Documents\\MyFile.txt"
);
028.
try
029.
{
030.
printFont =
new
Font(
"Arial"
, 10);
031.
PrintDocument pd =
new
PrintDocument();
032.
pd.PrintPage +=
new
PrintPageEventHandler
033.
(
this
.pd_PrintPage);
034.
pd.Print();
035.
}
036.
finally
037.
{
038.
streamToPrint.Close();
039.
}
040.
}
041.
catch
(Exception ex)
042.
{
043.
MessageBox.Show(ex.Message);
044.
}
045.
}
046.
047.
048.
private
void
pd_PrintPage(
object
sender, PrintPageEventArgs ev)
049.
{
050.
float
linesPerPage = 0;
051.
float
yPos = 0;
052.
int
count = 0;
053.
float
leftMargin = ev.MarginBounds.Left;
054.
float
topMargin = ev.MarginBounds.Top;
055.
string
line =
null
;
056.
057.
058.
linesPerPage = ev.MarginBounds.Height /
059.
printFont.GetHeight(ev.Graphics);
060.
061.
062.
while
(count < linesPerPage &&
063.
((line = streamToPrint.ReadLine()) !=
null
))
064.
{
065.
yPos = topMargin + (count *
066.
printFont.GetHeight(ev.Graphics));
067.
ev.Graphics.DrawString(line, printFont, Brushes.Black,
068.
leftMargin, yPos,
new
StringFormat());
069.
count++;
070.
}
071.
072.
073.
if
(line !=
null
)
074.
ev.HasMorePages =
true
;
075.
else
076.
ev.HasMorePages =
false
;
077.
}
078.
079.
080.
081.
private
void
InitializeComponent()
082.
{
083.
this
.components =
new
System.ComponentModel.Container();
084.
this
.printButton =
new
System.Windows.Forms.Button();
085.
086.
this
.ClientSize =
new
System.Drawing.Size(504, 381);
087.
this
.Text =
"Print Example"
;
088.
089.
printButton.ImageAlign =
090.
System.Drawing.ContentAlignment.MiddleLeft;
091.
printButton.Location =
new
System.Drawing.Point(32, 110);
092.
printButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
093.
printButton.TabIndex = 0;
094.
printButton.Text =
"Print the file."
;
095.
printButton.Size =
new
System.Drawing.Size(136, 40);
096.
printButton.Click +=
new
System.EventHandler(printButton_Click);
097.
098.
this
.Controls.Add(printButton);
099.
}
100.
101.
}