Printing Text in GDI+ using VB.NET

In this article I will explain about Printing Text in GDI+.
  • 5105

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? 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 buttons 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.

Figure2011_12.gif

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.

LISTING 11.21: The Browse Text File button click event handler


    Private Sub BrowseBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs)

        'Create an OpenFileDialog object
        Dim fdlg As New OpenFileDialog()

        'Set its properties
        fdlg.Title = "C# Corner Open File Dialog"
        fdlf.InitialDirectory = "C:\"
        fdlg.Filter = "Text files (*.txt | .txt | All files (*.*) | *.*"
        fdlg.FilterIndex = 2
        fdlg.RestoreDirectoty = True

        'Show dialog and set the selected file name
        'as the text of the text box

        If fldg.ShowDialog() = DialogResult.OK Then
            textBox1.Text = fdlg.FileName
        End If
    End Sub


Now let's add code for the Print Text File button click. First we add tow private variable to the application as follows:


Private verdana10Font As Font
Private reader As StreamReader

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. After that we create a PrintDocument object, and 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 Sub PrintTextFile_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        'Get the file name
        Dim filename As String = textBox1.Text.TosTring()

        'check if it's not empty
        If filename.Equals(String.Empty) Then
            MessageBox.Show("Enter a valid file name")
            textBox1.Focus()
            Return
        End If

        'Create a StreamReader object
        reader = New StreamReader(filename)

        'Create a Verdana font with size 10
        verdana10Font = New Font("Verdana", 10)

        'Create a PrintDocument object
        Dim pd As New PrintDocument()

        'Add PrintPage event handler
        pd.PrintPage += New PrintPageEventHandler(Me.PrintTextFileHandler)

        'Call Print Method
        pd.Print()

        'Close the reader
        If reader IsNot Nothing Then
            reader.Close()
        End If
    End Sub


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.GetHegiht method.

LISTING 11.23: Adding a print event handler


    Private Sub PrintTextFileHandler(ByVal sender As Object, ByVal ppeArgs As PrintPageEventArgs)
        'Get the Graphics object
        Dim g As Graphics = ppeArgs.Graphics
        Dim linesPerPage As Single = 0
        Dim yPos As Single = 0
        Dim count As Integer = 0

        'Read margins from PrintPageEventArgs
        Dim leftMargin As Single = ppeArgs.MarginBounds.Left
        Dim topMargin As Single = ppeArgs.MarginBounds.TOP
        Dim line As String = Nothing

        '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 AndAlso ((InlineAssignHelper(line, reader.REadLine())) IsNot Nothing)
            'Calculate the starting position
            yPos = topMargin + (count * verdana10Font.GetHeight(g))

            'Draw text
            g.DrawString(line, verdana10Font, Brushes.Black, leftMargin, yPose, New StringFormat())

            'Move to next line
            count += 1
        End While

        'If PrintPageEventArgs has more pages to print
        If line IsNot Nothing Then
            ppeArgs.HasMorePages = True
        Else
            ppeArgs.HasMorePages = False
        End If
    End Sub


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.

Conclusion

Hope the article would have helped you in understanding Printing Text in GDI+. Read other articles on GDI+ on the website.

Categories

More Articles

© 2020 DotNetHeaven. All rights reserved.