Printing Multiple Pages of a Text File in Windows Forms
The article has been updated on 8/02/2008 to support OpenFileDialog with filter for text files.
The System.Drawing.Graphics class provides functionality for drawing graphics or text to a screen or printer. In this article, we will explore the functions provided by Graphics class to print a text file with multiple pages.
Step1: Create a new Windows Form application. Drag and drop a textbox control and two buttons and rename it as ‘Browse’ and ‘Print’. Also drag and drop an ‘OpenFileDialog’ control. This control will be used to browse to the file that has to be printed. The filename will be displayed in the textbox.
Step 2: In the Form1.cs, add the following references:
System.Drawing
System.Drawing.Printing
System.IO
Step 3: Now set some properties of the OpenFileDialog as shown below:
Filter: txt files (*.txt)|*.txt
FilterIndex: 2
InitialDirectory: C:\
Title: Select a File to be printed
Step 4: Double click the Browse button. We will add code to select a text file and display the name of the file in the textbox.
C#
private void btnBrowse_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
txtFileNm.Text = openFileDialog1.FileName;
}
}
VB.NET
Private Sub btnBrowse_Click(ByVal sender As Object, ByVal e As EventArgs)
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
txtFileNm.Text = openFileDialog1.FileName
End If
End Sub
Step 5: Now declare a PrintDocument component in your form. Also declare a string that will be used to temporarily store the text to be printed.
C#
PrintDocument pd = new PrintDocument();
string strPrint;
VB.NET
Dim pd As PrintDocument = New PrintDocument()
Dim strPrint As String
Step 6: We will now create the Printing functionality. To do so, double click the Print button and add the following code. The comments explain the code clearly:
C#
private void btnPrint_Click(object sender, EventArgs e)
{
// Displays the document name in the print status or queue
pd.DocumentName = txtFileNm.Text;
// Associate PrintPage method with its event handler
pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
// Open the document
using (FileStream fs = new FileStream(pd.DocumentName, FileMode.Open))
// Read the contents of the document in a stream reader object
using (StreamReader sr = new StreamReader(fs))
{
strPrint = sr.ReadToEnd();
}
// Calling this method invokes the PrintPage event
pd.Print();
}
VB.NET
Private Sub btnPrint_Click(ByVal sender As Object, ByVal e As EventArgs)
' Displays the document name in the print status or queue
pd.DocumentName = txtFileNm.Text
' Associate PrintPage method with its event handler
AddHandler pd.PrintPage, AddressOf pd_PrintPage
' Open the document
Using fs As FileStream = New FileStream(pd.DocumentName, FileMode.Open)
' Read the contents of the document in a stream reader object
Using sr As StreamReader = New StreamReader(fs)
strPrint = sr.ReadToEnd()
End Using
End Using
' Calling this method invokes the PrintPage event
pd.Print()
End Sub
Step 7: The PrintPage event handler would look similar to the following:
C#
private void pd_PrintPage(object sender, PrintPageEventArgs e)
{
int charCount = 0;
int lineCount = 0;
// Measure the specified string 'strPrint'
// Calculate characters per line 'charCount'
// Calcuate lines per page that will fit within
// the bounds of the page 'lineCount' e.Graphics.MeasureString(strPrint, this.Font,
e.MarginBounds.Size, StringFormat.GenericTypographic,
out charCount, out lineCount);
// Determine the page bound and draw the string accordingly
e.Graphics.DrawString(strPrint, this.Font, Brushes.Black,
e.MarginBounds, StringFormat.GenericTypographic);
// Now remove that part of the string that has been printed.
strPrint = strPrint.Substring(charCount);
// Check if any more pages left for printing
if (strPrint.Length > 0)
e.HasMorePages = true;
else
e.HasMorePages = false;
}
VB.NET
Private Sub pd_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs)
Dim charCount As Integer = 0
Dim lineCount As Integer = 0
' Measure the specified string 'strPrint'
' Calculate characters per line 'charCount'
' Calcuate lines per page that will fit within
' the bounds of the page 'lineCount' e.Graphics.MeasureString(strPrint, Me.Font, e.MarginBounds.Size, StringFormat.GenericTypographic, charCount, lineCount)
' Determine the page bound and draw the string accordingly
e.Graphics.DrawString(strPrint, Me.Font, Brushes.Black, e.MarginBounds, StringFormat.GenericTypographic)
' Now remove that part of the string that has been printed.
strPrint = strPrint.Substring(charCount)
' Check if any more pages left for printing
If strPrint.Length > 0 Then
e.HasMorePages = True
Else
e.HasMorePages = False
End If
End Sub
Run the application and select a text file to be printed. The PrintPage event is fired for each page till the ‘HasMorePages’ property evaluates to false.
The source code of this article can be downloaded from here. I hope this article was useful and I thank you for viewing it.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of
DotNetCurry,
DNC Magazine for Developers,
SQLServerCurry and
DevCurry. He has also authored a couple of books
51 Recipes using jQuery with ASP.NET Controls and
The Absolutely Awesome jQuery CookBook.
Suprotim received the prestigious Microsoft MVP award for 17 consecutive years, until he resigned from the program in 2025. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.
Get in touch with him on Twitter @suprotimagarwal or at LinkedIn