Printer Settings

Table of contents:

Before writing our next printing application, let's examine printer settings. Printer settings specify the properties of a print process, such as the paper size, print quality, number of copies, number of pages, and so on. In this section we will first discuss how to access and set printer settings using the PrinterSettings class properties. Then we will write an application that allows us to read and set printer settings programmatically.

11.4.1 The PrinterSettings Class

The PrinterSettings object is the gateway to reading and setting printer settings. PrinterSettings specifies how a document will be printed during a print process.

After creating a PrinterSettings object instance, we usually use the PrintDocument.PrinterSettings or PageSettings.PrinterSettings property to access the PrinterSettings objects corresponding to the PrintDocument and PageSettings objects, respectively. We will discuss these in more detail in a moment.

The following code snippet creates a PrinterSettings object:


 
PrinterSettings prs = new PrinterSettings();

 

The PrinterSettings class provides the following 22 properties: CanDuplex, Collate, Copies, DefaultPageSettings, Duplex, FromPage, InstalledPrinters, IsDefaultPrinter, IsPlotter, IsValid, LandscapeAngle, MaximumCopies, MaximumPage, MinimumPage, PaperSizes, PaperSources, PrinterName, PrinterResolutions, PrintRange, PrintToFile, SupportsColor, and ToPage. In the sections that follow, we will discuss each of these properties in turn.

11.4.1.1 The InstalledPrinters Property

The InstalledPrinters static property returns the names of all available printers on a machine, including printers available on the network. This property returns all the printer names in a PrinterSettings.StringCollection object.

Listing 11.5 iterates through all the available printers on a machine.

Listing 11.5 Getting all installed printers on a machine

foreach(String printer in
 PrinterSettings.InstalledPrinters)
{
 string str = printer.ToString();
}

11.4.1.2 The PaperSizes Property

The PaperSizes property returns the paper sizes supported by a printer. It returns all the paper sizes in a PrinterSettings.PaperSizeCollection object.

Listing 11.6 iterates through all the available paper sizes.

Listing 11.6 Reading all available paper sizes

PrinterSettings prs = new PrinterSettings();
foreach(PaperSize ps in prs.PaperSizes)
{
 string str = ps.ToString();
}

11.4.1.3 The PrinterResolutions Property

The PrinterResolutions property returns all the resolutions supported by a printer. It returns all the printer resolutions in a PrinterSettings.PrinterResolutionCollection object that contains PrinterResolution objects.

Listing 11.7 reads the printer resolutions and adds them to a ListBox control. Here YourPrinterName is the name of the printer you want to use. If you do not set a printer name, the default printer will be used.

Listing 11.7 Getting printer resolution

PrinterSettings ps = new PrinterSettings();
// Set the printer name
ps.PrinterName = YourPrinterName;
foreach(PrinterResolution pr in ps.PrinterResolutions)
{
 listBox2.Items.Add(pr.ToString());
}

The PrinterResolution class, which represents the resolution of a printer, is used by the PrinterResolutions and PrinterResolution properties of PrinterSettings to get and set printer resolutions. Using these two properties, we can get all the printer resolutions available on a printer. We can also use it to set the printing resolution for a page.

The PrinterResolution class has three properties: Kind, X, and Y. The Kind property is used to determine whether the printer resolution is the PrinterResolutionKind enumeration type or Custom. If it's Custom, the X and Y properties are used to determine the printer resolution in the horizontal and vertical directions, respectively, in dots per inch. If the Kind property is not Custom, the value of X and Y each is 1.

11.4.1.4 The CanDuplex and Duplex Properties

The CanDuplex property is used to determine whether a printer can print on both sides of a page. If so, we can set the Duplex property to true to print on both sides of a page.

Listing 11.8 determines whether your printer can print on both sides of a page. If your program responds true, you have a very good printer.

Listing 11.8 Using the CanDuplex property

PrinterSettings ps = new PrinterSettings();
MessageBox.Show("Supports Duplex?");
MessageBox.Show("Answer = " + ps.CanDuplex.ToString());

The Duplex enumeration specifies the printer's duplex settings, which are used by PrinterSettings. The members of the Duplex enumeration are described in Table 11.1.

11.4.1.5 The Collate Property

The Collate property (both get and set) is used only if we choose to print more than one copy of a document. If the value of Collate is true, an entire copy of the document will be printed before the next copy is printed. If the value is false, all copies of page 1 will be printed, then all copies of page 2, and so on.

The code snippet that follows sets the Collate property of PrinterSettings to true:


 
PrinterSettings ps = new PrinterSettings();
ps.Collate=true;

 

11.4.1.6 The Copies Property

The Copies property (both get and set) allows us to enter the number of copies of a document that we want to print. Not all printers support this feature (in which case this setting will be ignored). The MaximumCopies property, which is described in Section 11.4.1.9, tells us how many copies the printer can print.

Table 11.1. Duplex members

Member

Description

Default

Default duplex setting

Horizontal

Double-sided, horizontal printing

Simplex

Single-sided printing

Vertical

Double-sided, vertical printing

Duplex Printing A Problem

Duplex printing (the ability to print on both sides of a page) is a feature usually found on higher-end laser and inkjet printers. It is generally found only on more expensive printers because either the printer needs to be able to print on both sides of a sheet, or it must have an internal mechanism to turn the page over and print on the other side.

Let's assume you have a low-end printer and need to print on both sides of the page. To do this, you would need to create a custom software solution. Let's also assume that your application is printing a 100-page text document. Because the document consists of text alone, this is not too difficult to achieve. You would simply read from a text stream and keep track of whether you have the space to print the next line. If not, you would tell the printer to go to another page. In this scenario you would end up with 100 single-sided pages.

So how do you get double-sided printing? In the tradition of good programming, you cheat, of course! The solution to this problem is to track the page number, and on the first pass print only odd-numbered pages (1, 3, 5, and so on). Once you have done this, display a dialog box that tells you to take all the sheets of paper just printed and reload them into the printer so they will be fed into the printer upside down. Now you can print the even-numbered pages (2, 4, 6, and so on). Voilà! The user gets duplex printing functionality from a cheap printer.

The following code sets the Copies property of PrinterSettings:


 
PrinterSettings ps = new PrinterSettings();
// We want 10 copies of our document
ps.Copies=10;

 

11.4.1.7 The IsPlotter Property

The IsPlotter property tells us if the printer we're using is actually a plotter that can accept plotter commands.

The following code snippet indicates whether the printer is a plotter:


 
PrinterSettings ps = new PrinterSettings();
MessageBox.Show(ps.IsPlotter.ToString());

 

11.4.1.8 The PrinterName and IsValid Properties

If we print without setting the PrinterName property, our printout will be sent to the default printer. The PrinterName property allows us to specify a printer to use. The IsValid property tells us whether the PrinterName value we have selected represents a valid printer on our system.

Listing 11.9 checks if the printer is valid.

Listing 11.9 Using the IsValid property

PrinterSettings ps = new PrinterSettings();
ps.PrinterName=("Invalid Printer Name");
MessageBox.Show("Is this a valid printer name?");
MessageBox.Show(ps.IsValid.ToString());

11.4.1.9 The MaximumCopies Property

The MaximumCopies property determines how many copies the printer can print. Some printers do not allow us to print more than one copy at a time.

Listing 11.10 reads the maximum number of copies that a printer can print.

Listing 11.10 Reading the maximum number of copies

PrinterSettings ps = new PrinterSettings();
MessageBox.Show("Maximum number of copies: ");
MessageBox.Show(ps.MaximumCopies);

11.4.1.10 The SupportsColor Property

The SupportsColor property tells us whether the current printer supports printing in color. It will return true if the printer supports color printing and false otherwise.

Listing 11.11 reads the value of the SupportsColor property to find out whether a printer supports colors.

Listing 11.11 Using the SupportsColor property

PrinterSettings ps = new PrinterSettings();
MessageBox.Show("Does this printer support color:");
MessageBox.Show(ps.SupportsColor.ToString());

11.4.1.11 Other PrinterSettings Properties

Besides the properties discussed already, the PrinterSettings class provides the additional properties listed in Table 11.2. We will discuss these properties in detail in our examples.

11.4.2 The PaperSize Class

Most printers can use papers of more than one size (height and width). The PaperSize class is used to read and set the paper size used by a printer.

The PaperSize class represents the size of paper used in printing. This class is used by PrinterSettings through its PaperSizes property to get and set the paper sizes for the printer.

Table 11.2. Other PrinterSettings properties

Property

Description

DefaultPageSettings

Returns the default page settings.

FromPage

Returns the page number of the first page to print. Both get and set.

IsDefaultPrinter

Returns true if the current printer is the default printer.

LandscapeAngle

Returns the angle, in degrees, by which the portrait orientation is rotated to produce the landscape orientation. Valid rotation values are 90 and 270 degrees. If landscape is not supported, the only valid rotation value is 0 degrees.

MaximumPage

Returns the maximum value of FromPage or ToPage that can be selected in a print dialog. Both get and set.

MinimumPage

Returns the minimum value of FromPage or ToPage that can be selected in a print dialog. Both get and set.

PrintRange

Returns the page numbers that the user has specified to be printed. Both get and set.

PrintToFile

Returns a value indicating whether the printing output is sent to a file instead of a port. Both get and set.

ToPage

Returns the page number of the last page to print. Both get and set.

The PaperSize class has four properties: Height, Kind, PaperName, and Width. Height, Width, and PaperName have both get and set access. The Height and Width properties are used to get and set the paper's height and width, respectively, in hundredths of an inch. The PaperName property is used to get and set the name of the type of paper, but it can be used only when the Kind property is set to Custom. The Kind property returns the type of paper.

We can construct custom paper sizes using the PaperSize class. Listing 11.12 reads the PaperSize properties.

Listing 11.12 Reading PaperSize properties

PrinterSettings ps = new PrinterSettings();
Console.WriteLine("Paper Sizes");
foreach(PaperSize psize in ps.PaperSizes)
{
 string str1 = psize.Kind.ToString();
 string str2 = psize.PaperName.ToString();
 string str3 = psize.Height.ToString();
 string str4 = psize.Width.ToString();
}

11.4.3 The PaperSource Class

The PaperSource class specifies the paper tray from which the printer retrieves the paper for the current printing task. This class is used by PrinterSettings through its PaperSources property to get and set the paper source trays that are available on the printer. The PaperSize class has two properties: Kind and SourceName. The Kind property returns an enumerated value for the paper source, and SourceName returns the name of the paper source as a string.

Listing 11.13 reads all the paper sources and displays them in a message box.

Listing 11.13 Reading paper sources

PrinterSettings ps = new PrinterSettings();
foreach(PaperSource p in ps.PaperSources)
{
 MessageBox.Show(p.SourceName);
}

11.4.4 The PrinterResolutionKind Enumeration

The PrinterResolutionKind enumeration specifies a printer resolution, as described in Table 11.3. This enumeration is used by the PrinterResolution, PrinterSettings, and PageSettings classes.

11.4.5 PrinterSettings Collection Classes

Besides the PrinterSettings class, the System.Drawing.Printing namespace provides three PrinterSettings collection classes. These collection classes provide members to count total items in a collection, and to add items to and remove items from a collection. These classes are

  1. PrinterSettings.PaperSizeCollection. A printer may support different kinds of papers, including papers of different sizes. This class returns a collection including all paper sizes supported by the printer. PaperSizeCollection contains PaperSizes objects.
  2. PrinterSettings.PaperSourceCollection. A printer may support different paper sources (trays). This class represents a collection of paper sources (trays) provided by a printer. PaperSourceCollection is available via the PaperSources property and contains PaperSource objects.
  3. PrinterSettings.PrinterResolutionCollection. A printer may support different resolutions. This class represents a collection of resolutions supported by a printer. PrinterResolutionCollection is accessible via the PrinterResolutions property and contains PrinterResolution objects.

Table 11.3. PrinterResolutionKind members

Member

Description

Custom

Custom resolution

Draft

Draft-quality resolution

High

High resolution

Low

Low resolution

Medium

Medium resolution

All of these collection classes provide Count and Item properties. The Count property returns the total number of items in a collection, and the Item property returns the item at the specified index. We will use these classes in our samples.

11.4.6 A Printer Settings Example

On the basis of the preceding discussion of printer settings, and of printerrelated classes and their members, let's write an application using these classes. In this application we will display available printers, the resolutions they support, available paper sizes, and other printer properties. This application will also allow us to set printer properties.

First we create a Windows application and add a combo box, two list boxes, three buttons, six check boxes, and two text boxes to the form. The final form looks like Figure 11.8. Then we add a reference to the System.Drawing.Printing namespace.

Figure 11.8. The printer settings form

graphics/11fig08.jpg

Next we write code. The Available Printers combo box displays all available installed printers on the machine in the ListBox control. We load all installed printers on the form's load event. As Listing 11.14 shows, we use the InstalledPrinters static property of PrinterSettings, which returns all installed printer names. We check if the installed printers count is more than 0 and add the installed printers to the combo box.

Listing 11.14 Reading all available printers

private void Form1_Load(object sender,
 System.EventArgs e)
{
 // See if any printers are installed
 if( PrinterSettings.InstalledPrinters.Count <= 0)
 {
 MessageBox.Show("Printer not found!");
 return;
 }
 // Get all the available printers and add them to the
 // combo box
 foreach(String printer in
 PrinterSettings.InstalledPrinters)
 {
 PrintersList.Items.Add(printer.ToString());
 }
}

The Get Printer Resolution button returns resolutions supported by a printer selected in ListBox1. The PrinterResolutions property of PrinterSettings returns the printer resolutions supported by the printer. Listing 11.15 reads all available resolutions for the selected printer in ListBox1 and adds them to ListBox2.

Listing 11.15 Reading printer resolutions

private void button2_Click(object sender,
 System.EventArgs e)
{
 // If no printer is selected
 if(PrintersList.Text == string.Empty)
 {
 MessageBox.Show("Select a printer from the list");
 return;
 }
 // Get the current selected printer from the
 // list of printers
 string str = PrintersList.SelectedItem.ToString();
 // Create a PrinterSettings object
 PrinterSettings ps = new PrinterSettings();
 // Set the current printer
 ps.PrinterName = str;
 // Read all printer resolutions and add
 // them to the list box
 foreach(PrinterResolution pr
 in ps.PrinterResolutions)
 {
 ResolutionsList.Items.Add(pr.ToString());
 }
}

The Get Paper Size button returns the available paper sizes. Again we use the PaperSizes property of PrinterSettings, which returns all available paper sizes. Listing 11.16 reads all available paper sizes and adds them to the list box.

Listing 11.16 Reading paper sizes

private void button3_Click(object sender,
 System.EventArgs e)
{
 // If no printer is selected
 if(PrintersList.Text == string.Empty)
 {
 MessageBox.Show("Select a printer from the list");
 return;
 }
 // Create printer settings
 PrinterSettings prs = new PrinterSettings();
 // Get the current selected printer from the
 // list of printers
 string str = PrintersList.SelectedItem.ToString();
 prs.PrinterName = str;
 // Read paper sizes and add them to the list box
 foreach(PaperSize ps in prs.PaperSizes)
 {
 PaperSizesList.Items.Add(ps.ToString());
 }
}

The Get Printer Properties button gets the printer properties and sets the check boxes and text box controls according to the values returned. The Get Printer Properties button click event handler code is given in Lising 11.17. We read many printer properties that were discussed earlier in this chapter.

Listing 11.17 Reading printer properties

private void GetProperties_Click(object sender,
 System.EventArgs e)
{
 // If no printer is selected
 if(PrintersList.Text == string.Empty)
 {
 MessageBox.Show("Select a printer from the list");
 return;
 }
 PrinterSettings ps = new PrinterSettings();
 string str = PrintersList.SelectedItem.ToString();
 ps.PrinterName = str;
 // Check if the printer is valid
 if(!ps.IsValid)
 {
 MessageBox.Show("Not a valid printer");
 return;
 }
 // Set printer name and copies
 textBox1.Text = ps.PrinterName.ToString();
 textBox2.Text = ps.Copies.ToString();

 // If printer is the default printer
 if (ps.IsDefaultPrinter == true)
 IsDefPrinterChkBox.Checked = true;
 else
 IsDefPrinterChkBox.Checked = false;
 // If printer is a plotter
 if (ps.IsPlotter)
 IsPlotterChkBox.Checked = true;
 else
 IsPlotterChkBox.Checked = false;
 // Duplex printing possible?
 if (ps.CanDuplex)
 CanDuplexChkBox.Checked = true;
 else
 CanDuplexChkBox.Checked = false;
 // Collate?
 if (ps.Collate)
 CollateChkBox.Checked = true;
 else
 CollateChkBox.Checked = false;
 // Printer valid?
 if (ps.IsValid)
 IsValidChkBox.Checked = true;
 else
 IsValidChkBox.Checked = false;
 // Color printer?
 if (ps.SupportsColor)
 SuppColorsChkBox.Checked = true;
 else
 SuppColorsChkBox.Checked = false;
}

Now let's run the application. By default, the Available Printers combo box displays all available printers. Select a printer from the list, and click the Get Printer Resolution button, which displays the printer resolutions supported by the selected printer. Also click on the Get Paper Size and Get Printer Properties buttons. The final output of the application is shown in Figure 11.9.

Figure 11.9. Reading printer properties

graphics/11fig09.jpg

We will be using many PrinterSettings class members throughout this chapter.

GDI+: The Next-Generation Graphics Interface

Your First GDI+ Application

The Graphics Class

Working with Brushes and Pens

Colors, Fonts, and Text

Rectangles and Regions

Working with Images

Advanced Imaging

Advanced 2D Graphics

Transformation

Printing

Developing GDI+ Web Applications

GDI+ Best Practices and Performance Techniques

GDI Interoperability

Miscellaneous GDI+ Examples

Appendix A. Exception Handling in .NET



GDI+ Programming with C#
GDI+ Programming with C#
ISBN: 073561265X
EAN: N/A
Year: 2003
Pages: 145

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net