Print a text file in C#

This example lets you select a printer and file, and then print the file on the selected printer. (Actually this version just displays a print preview. To send the file directly to the selected printer, see the example Send a printout directly to a specific printer in C#.)
When the program starts, it executes the following initialization code.

// Populate the list of printers.
private void Form1_Load(object sender, EventArgs e)
{
    // Find all of the installed printers.
    foreach (string printer in PrinterSettings.InstalledPrinters)
    {
        cboPrinter.Items.Add(printer);
    }

    // Find and select the default printer.
    try
    {
        PrinterSettings settings = new PrinterSettings();
        cboPrinter.Text = settings.PrinterName;
    }
    catch
    {
    }

    // Initially select the source code file.
    string file_path = Application.StartupPath;
    if (file_path.EndsWith(@"\bin\Debug"))
        file_path = file_path.Substring(0, file_path.Length - 10);
    if (file_path.EndsWith(@"\bin\Release"))
        file_path = file_path.Substring(0, file_path.Length - 12);
    if (file_path.EndsWith(@"\"))
        file_path = file_path.Substring(0, file_path.Length - 1);
    file_path += @"\Form1.cs";
    txtFile.Text = file_path;
}

The code first initializes a ComboBox with the names of the available printers. It sets the ComboBox's initial selection to the default printer. (See Determine the default printer in C# for details.) It then copies name of the example's Form1.cs file into the File TextBox.

If you enter or select a file name and then click Preview, the following code displays a print preview for the file.

// The text contained in the file.
private string FileContents;

// Preview the selected file.
private void btnPreview_Click(object sender, EventArgs e)
{
    // Read the file's contents.
    try
    {
        FileContents = File.ReadAllText(txtFile.Text).Trim();
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error reading file " + txtFile.Text +
            ".\n" + ex.Message);
        return;
    }

    // Display the print preview dialog.
    ppdTextFile.ShowDialog();
}

This code uses the System.IO.File class's ReadAllText method to save the file's contents into the string FileContents. It then displays the PrintPreviewDialog named ppdTextFile.

At design time, I added the PrintPreviewDialog to the form. I also added a PrintDocument named pdocTextFile to the form and set the PrintPreviewDialog's Document property equal to pdocTextFile.

When the code calls the dialog's ShowDialog method, it asks pdocTextFile to generate the printout that it should display. The pdocTextFile component raises its PrintPage event to let the program create the printout. The following code shows the PrintPage event handler.

// Print a page of the text file.
private void pdocTextFile_PrintPage(object sender, PrintPageEventArgs e)
{
    // Make a font for printing.
    using (Font font = new Font("Courier New", 10))
    {
        // Make a StringFormat to align text normally.
        using (StringFormat string_format = new StringFormat())
        {
            // See how much of the remaining text will fit.
            SizeF layout_area = new SizeF(
                e.MarginBounds.Width, e.MarginBounds.Height);
            int chars_fitted, lines_filled;
            e.Graphics.MeasureString(FileContents, font,
                layout_area, string_format,
                out chars_fitted, out lines_filled);

            // Print as much as will fit.
            e.Graphics.DrawString(
                FileContents.Substring(0, chars_fitted),
                font, Brushes.Black, e.MarginBounds,
                string_format);

            // Remove the printed text from the string.
            FileContents = FileContents.Substring(chars_fitted).Trim();
        }
    }

    // See if we are done.
    e.HasMorePages = FileContents.Length > 0;
}

The event handler creates Font and StringFormat objects to use when printing. It then uses the techniques described in See how much text can fit in a rectangle in C# to see how much of the file's contents will fit within the margins of the printed page. The event handler draws that much text and removes the printed text from the FileContents variable.

If FileContents contains more text, the event handler sets e.HasMorePages to true to indicate that the PrintDocument should generate more pages of printout.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.