Printing Multiple Pages of a Text File in Windows Forms

Posted by: Suprotim Agarwal , on 2/9/2008, in Category WinForms & WinRT
Views: 30524
Abstract: 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.
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.
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
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 a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Anubhava on Monday, February 25, 2008 12:33 AM
Hi,
Can u Help me for Proxy Software.
Comment posted by chendil on Monday, March 31, 2008 3:38 AM
Realy cool and informative..
Comment posted by on Wednesday, August 20, 2008 12:18 PM
<http://www.mvps.org/dotnet/dotnet/samples/printing/downloads/PrintFramework.zip>
Comment posted by skype on Tuesday, October 7, 2008 11:38 AM
good
Comment posted by zynaps on Wednesday, May 11, 2011 9:03 AM
thank you

Categories

JOIN OUR COMMUNITY

POPULAR ARTICLES

FREE .NET MAGAZINES

Free DNC .NET Magazine

Tags

JQUERY COOKBOOK

jQuery CookBook