Code: Printing a Text File (Visual C#)

Code: Printing a Text File (Visual C#)

Visual Studio .NET 2003

This example demonstrates printing a text file.


System.IO.StreamReader fileToPrint;
System.Drawing.Font printFont;
private void printButton_Click(object sender, EventArgs e)
   string printPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
   fileToPrint = new System.IO.StreamReader(printPath + @"\myFile.txt");
   printFont = new System.Drawing.Font("Arial", 10);

private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
   float yPos = 0f;
   int count = 0;
   float leftMargin = e.MarginBounds.Left;
   float topMargin = e.MarginBounds.Top;
   string line = null;
   float linesPerPage = e.MarginBounds.Height/printFont.GetHeight(e.Graphics);
   while (count < linesPerPage)
      line = fileToPrint.ReadLine();
      if (line == null)
      yPos = topMargin + count * printFont.GetHeight(e.Graphics);
      e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
   if (line != null)
      e.HasMorePages = true;

Compiling the Code

This example requires:

  • A Button control named printButton with a Click event handler.
  • A PrintDocument component named printDocument1 with a PrintPage event handler.

This example further assumes that you have a text file named myFile.txt on your desktop. The example code replaces the existing event handlers.

Robust Programming

File operations should be enclosed within appropriate try...catch...finally blocks. Always call StreamReader.Close when you have finished using it.

The following conditions may cause an exception:

  • You do not have permission to access the printer.
  • You do not have permission to access the file system.
  • There is no printer installed.
  • The Arial font is not installed.


In order to run this example, you must have permission to access the file system and the printer.

See Also

Graphics Programming Example Topics | Introduction to the Windows Forms PrintDocument Component | StreamReader Class | PrintDocument Class

© 2015 Microsoft