So far we have printed simple text and graphics items from the program itself. How about reading a text file and printing it from our program? Do you remember the GDI+ editor from Chapter 5? We can make the editor open a text file and add print functionality to print the text file. In this section we will read a text file and print it.
As usual, we create a Windows application and add a reference to the System.Drawing.Printing namespace. We then add a text box and four buttons to the form. We also change the Name and Text properties of the button controls. The final form looks like Figure 11.12. As you might guess, the Browse Text File button allows us to browse for text files.
Figure 11.12. The form with text file printing options

The code for the Browse Text File button is given in Listing 11.21. This button allows you to browse a file and adds the selected file name to the text box. Clicking the Print Text File button prints the selected text file. We use an OpenFileDialog object to open a text file and set textBox1.Text as the selected file name. The functionality of the Print Text and Print Events buttons is obvious.
Note
C# Corner's FAQ (http://www.c-sharpcorner.com/faq.asp) includes a long list of .NET how-tos and frequently asked questions and contains the code for these simple functionalities.
Listing 11.21 The Browse Text File button click event handler
private void BrowseBtn_Click(object sender,
System.EventArgs e)
{
// Create an OpenFileDialog object
OpenFileDialog fdlg = new OpenFileDialog();
// Set its properties
fdlg.Title = "C# Corner Open File Dialog" ;
fdlg.InitialDirectory = @"c:" ;
fdlg.Filter =
"Text files (*.txt)|*.txt|All files (*.*)|*.*" ;
fdlg.FilterIndex = 2 ;
fdlg.RestoreDirectory = true ;
// Show dialog and set the selected file name
// as the text of the text box
if(fdlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fdlg.FileName ;
}
}
Now let's add code for the Print Text File button click. First we add two private variables to the application as follows:
private Font verdana10Font; private StreamReader reader;
Then we proceed as shown in Listing 11.22. The code is pretty simple. First we make sure that the user has selected a file name. Then we create a StreamReader object and read the file by passing the file name as the only argument. Next we create a font with font family Verdana and size 10 (see Chapter 5 for more on fonts). After that we create a PrintDocument object, add a PrintPage event handler, and call the Print method. The rest is done by the PrintPage event handler.
Note
The StreamReader class is defined in the System.IO namespace.
Listing 11.22 The Print Text File button click event handler
private void PrintTextFile_Click(object sender,
System.EventArgs e)
{
// Get the file name
string filename = textBox1.Text.ToString();
// Check if it's not empty
if(filename.Equals(string.Empty))
{
MessageBox.Show("Enter a valid file name");
textBox1.Focus();
return;
}
// Create a StreamReader object
reader = new StreamReader(filename);
// Create a Verdana font with size 10
verdana10Font = new Font("Verdana", 10);
// Create a PrintDocument object
PrintDocument pd = new PrintDocument();
// Add PrintPage event handler
pd.PrintPage += new PrintPageEventHandler
(this.PrintTextFileHandler);
// Call Print method
pd.Print();
// Close the reader
if(reader != null)
reader.Close();
}
The code for the PrintPage event handler PrintTextFileHandler is given in Listing 11.23. Here we read one line at a time from the text file, using the StreamReader.ReadLine method, and call DrawString, which prints each line until we reach the end of the file. To give the text a defined size, we use the verdana10Font.GetHeight method.
Note
See Chapter 3 and 5 for details about the DrawString method and fonts, respectively.
Listing 11.23 Adding a print-page event handler
private void PrintTextFileHandler(object sender,
PrintPageEventArgs ppeArgs)
{
// Get the Graphics object
Graphics g = ppeArgs.Graphics;
float linesPerPage = 0;
float yPos = 0;
int count = 0;
// Read margins from PrintPageEventArgs
float leftMargin = ppeArgs.MarginBounds.Left;
float topMargin = ppeArgs.MarginBounds.Top;
string line = null;
// Calculate the lines per page on the basis of
// the height of the page and the height of
// the font
linesPerPage = ppeArgs.MarginBounds.Height /
verdana10Font.GetHeight(g);
// Now read lines one by one, using StreamReader
while(count < linesPerPage &&
((line = reader.ReadLine()) != null))
{
// Calculate the starting position
yPos = topMargin + (count *
verdana10Font.GetHeight(g));
// Draw text
g.DrawString(line, verdana10Font, Brushes.Black,
leftMargin, yPos, new StringFormat());
// Move to next line
count++;
}
// If PrintPageEventArgs has more pages
// to print
if(line != null)
ppeArgs.HasMorePages = true;
else
ppeArgs.HasMorePages = false;
}
You should be able to add code for the Print Text and Print Events buttons yourself. Their functionality should be obvious.
Now run the application, browse a text file, and hit the Print Text File button, and you should be all set.
Note
Using the same method, you can easily add printing functionality to the GDI+ editor. You can add a menu item called Print to the editor that will print an opened text file.
GDI+: The Next-Generation Graphics Interface
Your First GDI+ Application
The Graphics Class
Working with Brushes and Pens
Colors, Fonts, and Text
Rectangles and Regions
Working with Images
Advanced Imaging
Advanced 2D Graphics
Transformation
Printing
Developing GDI+ Web Applications
GDI+ Best Practices and Performance Techniques
GDI Interoperability
Miscellaneous GDI+ Examples
Appendix A. Exception Handling in .NET