Printing Text in GDI+


This article has been excerpted from book "Graphics Programming with GDI+".

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.

Figure 11.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 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";
            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)
            {
                textBox1.Text = fdlg.FileName;
            }
        }


Now let's add code for the Print Text File button click. First we add tow private variable 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. 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 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.GetHegiht method.

LISTING 11.23: Adding a print 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, yPose, 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.

Conclusion

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

bookGDI.jpg This book teaches .NET developers how to work with GDI+ as they develop applications that include graphics, or that interact with monitors or printers. It begins by explaining the difference between GDI and GDI+, and covering the basic concepts of graphics programming in Windows.

Up Next
    Ebook Download
    View all
    Learn
    View all