The Print Dialog Box

Introduction to Printing

Besides saving or opening files, another operation users perform on a document consists of printing it. Printing is the ability to render, on paper, the result of a document or the contents of various controls. This is performed using an external device called a printer peripheral or simply a printer. To do this, users need access to a printer device.

There are two main ways users print a document. They can ask the application they are using to send the document directly to a printer or they can use a dialog box to decide how the printing should be done.

Practical LearningPractical Learning: Introducing Printing

  1. Save the folling icons in your computer:
    Calculator Print Close
  2. Start Microsoft Visual Studio
  3. Create a new Windows Forms App named MachineDepreciations1
  4. In the Solution Explorer, right-click Form1.cs and click Rename
  5. Type DoubleDecliningBalance (to get DoubleDecliningBalance.cs) and press Enter twice
  6. In the Toolbox, expand Components, click ImageList and click the form
  7. Below the form, right-click imageList1 and click Choose Images
  8. Keep clicking the Add button and add the above three icons

Introduction to the Print Dialog Box

One of the ways users print consists of sending the document to the printer. To directly send a document to the printer, you need to make sure that the control, whose value needs to be printed, supports printing. To accommodate the users of your application, you can provide a menu item or a button they would click. An example of such a button would be Print . To print, the user can click this button. With this type of printing, when the user decides to print, the whole document would be printed "as is", in color if the document is colored and if the printer supports colors. If there is more than one printer, the computer would use what is known as the default printer.

If you want users to be able to configure or customize the printing process, Microsoft Windows provides a common dialog box called Print. Here is an example:

The Print dialog box allows a user to select a printer if more than one is available. The user can decide either to print the whole document, to print a range of pages, or to print a portion of the document that was previously selected. The user can also decide on the number of copies to print from the document, the range specified, or the selected portion. Furthermore, the user can access the particular characteristics of the selected printer and specify how the printer should perform the job. For example, if the selected printer can print in color and the document is in color but the user wants to print in black and white, he or she can specify this using the Properties button.

Providing a Printer

To provide the users with the ability to customize printing through the Print dialog box, you can add a PrintDialog object Print Dialog from the Dialogs section of the Toolbox to your form. The PrintDialog control is implemented through the PrintDialog class of the System.Windows.Forms namespace:

public sealed class PrintDialog : System.Windows.Forms.CommonDialog

To programmatically create a PrintDialog object, you can declare a variable of type PrinterDialog. Here is an example:

private void btnPrintDocument(object sender, EventArgs e)
{
    PrintDialog dlgPrint = new PrintDialog();
}

To present the Print dialog box to the user, you can call its ShowDialog() method. Here is an example:

private void btnPrintDocument(object sender, EventArgs e)
{
    PrintDialog dlgPrint = new PrintDialog();
    
    dlgPrint.ShowDialog();
}

Practical LearningPractical Learning: Providing a Print Dialog Box

  1. In the Toolbox, expand Printing
  2. In the Printing section, click the PrintDialog button Print Dialog and click the form

The Printing Process

The Document to Print

In order to print, the Print dialog box must be given a document to print. This means that you must first prepare a document prior to printing. To support this, the .NET Framework provides a class named PrintDocument:

public class PrintDocument : System.ComponentModel.Component

That class is defined in the System.Drawing.Printing namespace. This class is represented in the Toolbox by the PrintDocument button . Based on this, to prepare a document for printing, you can either add a PrintDocument object to your project or declare a variable of type PrintDocument. Here is an example:

using System.Drawing.Printing;

namespace PrintingIntroduction
{
    public partial class Exercise : Form
    {
        Button btnPrint;

        public Exercise()
        {
            InitializeComponent();

            btnPrint = new Button();
            btnPrint.Location = new Point(12, 12);
            btnPrint.Text = "&Print...";
            btnPrint.Click += (sender, e) =>
            {
                PrintDialog dlgPrint = new PrintDialog();
                
                PrintDocument docPrint = new PrintDocument();

                dlgPrint.Document = docPrint;
                dlgPrint.ShowDialog();
            };

            Controls.Add(btnPrint);
        }
    }
}

After creating the document to print through a PrintDocument object, you can associate it with a Print Dialog. To support this, the PrintDialog class is equipped with a property named Document:

public System.Drawing.Printing.PrintDocument? Document { get; set; }

To specify the object that would carry the printing, you can assign the PrintDocument object to a PrintDialog.Document property. Here is an example:

System.Void btnPrint_Click(System.Object  sender, System.EventArgs  e)
{
    PrintDialog   dlgPrint = new PrintDialog;
    PrintDocument docPrint = new PrintDocument;

    dlgPrint.Document = docPrint;
    dlgPrint.ShowDialog();
}

A document to print can be made of only one or many pages. Each page has a number of characteristics. The characteristics of a page are controlled by a class named PageSettings. To support printer settings, the PrintDocument class is equipped with a property named PageSettings of the class with the same name:

public System.Drawing.Printing.PrinterSettings PrinterSettings { get; set; }

which itself is based on the PageSettings class. The PageSettings class is defined in the System.Drawing.Printing namespace. This class holds the dimensions of the page, the values of the margins applied on the page, the tray that would supply the paper (since some printers have many trays), the printer resolution, whether the page would be printed in color or black and white, whether the page would be printed in Portrait or Landscape orientation, etc. If you don't want to specify these characteristics, you can set the PrintDocument.PageSettings property to DefaultPageSettings.

If you know the name of the document to be printed, you can assign it to the PrintDocument.DocumentName property. Here is an example:

void btnPrintDocument(object sender, EventArgs e)
{
    PrintDialog dlgPrint = new PrintDialog();
    PrintDocument docPrint = new PrintDocument();

    dlgPrint.Document = docPrint;
    dlgPrint.ShowDialog();
}

To actually print the document, you can call the PrintDocument.Print() method. Its syntax is:

public void Print();

Practical LearningPractical Learning: Providing the Document to Print

Events Related to Printing

When the PrintDocument.Print() method is called, the printing process would start by firing an event named BeginPrint. This event occurs before the first page is printed. The BeginPrint event is of type PrintEventArgs which does not hold any particular information, especially for the BeginPrint event. This event allows you to take some early actions, if necessary, before the printer receives the job.

Once the printer is ready, the application would then need to know what needs to be printed on the paper. At this time, the PrintPage event is fired. The PrintPage event is of type PrintPageEventArgs. The PrintPageEventArgs class allows you to fully customize the page of the document to be printed. For example, it is equipped with a Graphics property that allows you to "draw" anything you want on the paper. The PrintPageEventArgs class also allows you to get the location and dimensions of the area to be printed. This is represented by the PageBounds property, which produces a Rectangle object.

Once the PrintDocument object is ready, you must pass it to the Print dialog box. To do that, assign the name of the PrintDocument variable to the PrintDialog.Document property.

Practical LearningPractical Learning: Preparing Priting

  1. Design the form as follows:

    Machine Depreciation - Double Declining Balance

    Control (Name) Text Text Align Other Properties
    ImageList ilIcons      
    PrintDocument docPrint      
    PrintDialog dlgPrint     Document: docPrint
    GroupBox   Depreciation Estimation    
    Label   Machine Cost:    
    TextBox txtMachineCost   Right  
    Label   Estimated Life:    
    TextBox txtEstimatedLife   Right  
    Label   Years    
    Button btnCalculate C&alculate   ImageList: ilIcons
    ImageIndex: 0
    ImageAlign: MiddleLeft
    Label   Declining Rate:    
    TextBox txtDecliningRate   Right  
    Label   Depreciation First Year:    
    Button btnPrintDepreciationSummary &Print Depreciation   ImageList: ilIcons
    ImageIndex: 1
    ImageAlign: MiddleLeft
    Button btnClose &Close   ImageList: ilIcons
    ImageIndex: 2
    ImageAlign: MiddleLeft
    Label   Book Value at    
    Label   Book Value at    
    ListView lvwDepreciations     FullRowSelect: True
    GridLines: True
    View: Details

    List View Columns

    (Name) Text TextAlign Width
    colYear Year    
    colBeginningOfYear Beginning of Year Right 150
    colDepreciationForYear Depreciation for Year Right 200
    colEndOfYear End of Year Right 105
  2. On the form, double-click the Calculate button
  3. Return to the form
  4. On the bar below the form, double-click docPrint to generate its default event
  5. Return to the form and double-click the &Print Depreciation
  6. Return to the form and double-click the Close button
  7. Implement the events as follows:
  8. To execute the application, on the main menu, click Debub -> Start Without Debugging:

    College Park Auto Repair

  9. In the indicated text boxes, type the following values:
    Machine Cost:   24,886.97
    Estimated Life: 20
  10. Click the Calculate button:

    Values Conversion - Metric System

  11. Click the Print Depreciation button
  12. Click the Close button

Introduction to Printer Settings

In the above example, we saw a somewhat simplistic way of making the Print dialog box available to the user. This dialog box offers many options defined as the Printer Settings. To support the various options of a Print dialog box, the .NET Framework provides a class named PrintDialog:

public class PrinterSettings : ICloneable

This is equipped with a default constructor. Therefore, to use this class, you can declare a variable of it. To let you controls tha characteristics of a Print Dialog box, the PrintDialog class is equipped with a property named PrinterSettings, which is of type PrinterSettings:

public System.Drawing.Printing.PrinterSettings PrinterSettings { get; set; }

To apply the characteristics of this property, if you had created a PrinterSettings object, you can then assign it to the PrintDialog.PrinterSettings. This can be done as follows:

private void btnPrintDepreciationSummary_Click(object sender, EventArgs e)
{
    PrinterSettings pss = new PrinterSettings();
    
    dlgPrint.PrinterSettings = pss;
    
    if (dlgPrint.ShowDialog() == DialogResult.OK)
    {
        docPrint.Print();
    }
}

A Name for a Printer

The first option presented to the user is the name of the printer to be used. Because there can be many printers available to the user, the printers may be represented in a combo box:

Print

The available printers may also be presented as a list view:

Print

The Name combo box in the Printer section or the Select Printer list view allows the user to select the printer that will handle the job. If you are writing a universal application and cannot predict what printer(s) the user would have, you would not be concerned with this characteristic. If you are writing an application for a special company or you are creating a particular application and you know for sure what printer should be used to print the current document, then you can specify the printer to use. To support this, the PrinterSettings class is equipped with a property named PrinterName:

public string PrinterName { get; set; }

To use this property, assign the (exact) name of the printer to the PrinterSettings.PrinterName property. Here is an example that explicitly asks the compiler to select a printer with the indicated name:

private void btnPrintDepreciationSummary_Click(object sender, EventArgs e)
{
    PrinterSettings pss = new PrinterSettings();
            
    pss.PrinterName = "HP095017 (HP OfficeJet Pro 8710)";
            
    dlgPrint.PrinterSettings = pss;
            
    if (dlgPrint.ShowDialog() == DialogResult.OK)
    {
        docPrint.Print();
    }
}

On the other hand, if for some reason you want to know what printer the user selected to print the document, you can get the value of this PrinterName property.

The Status of a Printer

Under the Name combo box, the labels provide the status of the selected printer (whether it is ready or not), the type of printer (such as its manufacturer), its location (such as where in the building the printer is located; the person who installed the printer or is managed the printers might have put this information), and an optional comment (this information is created by the person who installed the printer or it can be changed in the printer's properties).

The Properties or Preferences of a Printer

After selecting the printer, the user can access the properties of that particular printer. Different printers support different options. To configure the printed paper based on the selected printer, the user can click either Properties or Preferences. This opens the Document Properties or the Printing Preferences dialog box. The content of this dialog box (highly) depends on the printer that was selected but some characteristics are shared among printers.

Printing to a File

On the lower-right side of the Printer section or of the Select Printer section, there is a check box labeled Print To File. When this button is checked, the document is transformed into a file rather than being printed. In this case, if the user clicks OK or Print, a dialog box would come up, asking the user to specify the path and a name for the new file that will be created. The appearance of that dialog box depends. Here is an example:

To support printing to a file, the PrinterSettings class is equipped with a read-write Boolean property named PrintToFile:

public bool PrintToFile { get; set; }

If you want the Print To File check box to be checked, set the PrinterSettings.PrintFoFile property to true. Its default value is false, which lets the user decide whether to check it or not.

After selecting the printer and deciding whether to physically print or to only create a printed file, the user can click OK.

The Pages to Print

If the document is made of only one page, it would be printed. If the document contains more than one page, the user may want to print only one page, a range of pages, or all pages. The user can also select a section in the document and print only that section. This decision is made using the Page Range section and is controlled by the PrintRange property:

public PrintRange PrintRange { get; set; }

This section provides four radio buttons. The first radio button labeled All is selected by default and allows the user to print the whole document. By default, the second radio button is disabled. If the user had selected a section of the document to print, then the second radio button, labeled Selection would be enabled:

This allows the user to still specify whether to print the whole document or only the section that was selected. If the document contains more than one page, the user can navigate to a particular page and decide to print only that page using the Current Page radio button. Again, if the document contains more than one page, the user can specify a range of pages to print. All these options are usually left up to the user. On the other hand, if you want to specify the range of pages to print, you can use the PrinterSettings.FromPage and the ToPage properties:

public int FromPage { get; set; }
public int ToPage { get; set; }

If you want to specify the limits of ranges allowed to the user, use the MinimumPage and the MaximumPage properties:

public int MinimumPage { get; set; }
public int MaximumPage { get; set; }

On the right side of the Page Range section, a spin button allows the user to specify the number of copies to make when printing. If you want to specify this number by default, assign the desired value to the Copies property:

public short Copies { get; set; }

If the user (or you) set this number to a value higher than 1, then the printed papers can be collated or not. This is specified using the Collate check box. If you want to programmatically collate the pages or not, change the Boolean value of the Collate property:

public bool Collate { get; set; }

Previous Copyright © 2004-2024, FunctionX Monday 14 February 2022 Next