Select and print multiple files in C#

This example lets you select multiple files for printing. You can use it, for example, to print all of the .cs files in a project's directory.

Select a printer from the ComboBox at the top. Enter or select a directory and enter a file matching pattern. Then click List Files to see a list of files matching the pattern. Finally check the files you want to print and click Print.

This example uses techniques described in several previous posts.

The following code is the heart of the printing procedure.

// Print the selected files.
private void btnPrint_Click(object sender, EventArgs e)
{
    // Select the desired printer.
    pdocFile.PrinterSettings.PrinterName = cboPrinter.Text;

    // Print the checked files.
    foreach (string filename in clbFiles.CheckedItems)
    {
        Console.WriteLine("Printing: " + filename);

        // Get the file's name without the path.
        FileInfo file_into = new FileInfo(filename);
        string short_name = file_into.Name;

        // Set the PrintDocument's name for use by the printer queue.
        pdocFile.DocumentName = short_name;

        // Read the file's contents.
        try
        {
            FileContents = File.ReadAllText(filename).Trim();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error reading file " + filename +
                ".\n" + ex.Message);
            return;
        }

        // Print.
        pdocFile.Print();
    }

    MessageBox.Show("Spooled " + clbFiles.CheckedItems.Count +
        " files for printing.");
}

The code sets the PrintDocument's PrinterSettings.PrinterName property so the PrintDocument sends output to the selected printer. It sets the document's DocumentName property to the file's name without the path so you can see the file's name in the printer's spool.

Next the code loops over the files that are checked in the CheckedListBox. For each checked file, the code stores the file's text in the variable FileContents. It then calls the PrintDocument's Print method to print the file. See the example Print a text file in C# for information on how the program prints the file.

After it has finished, the program displays a message telling you how many files it scheduled for printing.

   

 

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.