8.13 Print a Simple Document


Problem

You need to print text or images.

Solution

Handle the PrintDocument.PrintPage event, and use the DrawString and DrawImage methods of the Graphics class to print data to the page.

Discussion

.NET uses an asynchronous event-based printing model. To print a document, you create a System.Drawing.Printing.PrintDocument instance, configure its properties, and then call its Print method, which schedules the print job. The common language runtime will then fire the BeginPrint , PrintPage , and EndPrint events of the PrintDocument class on a new thread. You handle these events and use the provided System.Drawing.Graphics object to output data to the page. Graphics and text are written to a page in exactly the same way as you draw to a window using GDI+. However, you might need to track your position on a page, because every Graphics class method requires explicit coordinates that indicate where to draw.

Printer settings are configured through the PrintDocument.PrinterSettings and PrintDocument.DefaultPageSettings properties. The PrinterSettings property returns a full PrinterSettings object (as described in recipe 8.12), which identifies the printer that will be used. The DefaultPageSettings property provides a full PageSettings object that specifies printer resolution, margins, orientation, and so on. You can configure these properties in code, or you can use the System.Windows.Forms.PrintDialog class to let the user make the changes using the standard Windows print dialog (shown in Figure 8.8). In the print dialog box, the user can select a printer and choose a number of copies. The user can also click the Properties button to configure advanced settings such as page layout and printer resolution. Finally, the user can either accept or cancel the print operation by clicking OK or Cancel.

click to expand
Figure 8.8: The PrintDialog .

Before using the PrintDialog class, you must explicitly attach it to a PrintDocument object by setting the PrintDialog.Document property. Then any changes the user makes in the print dialog will be automatically applied to the PrintDocument object.

The following example provides a form with a single button. When the user clicks the button, the application creates a new PrintDocument , allows the user to configure print settings, and then starts an asynchronous print operation (provided the user clicks OK). An event handler responds to the PrintPage event and writes several lines of text and an image.

 using System; using System.Windows.Forms; using System.Drawing; using System.Drawing.Printing; public class SimplePrint : System.Windows.Forms.Form {     private System.Windows.Forms.Button cmdPrint;     // (Designer code omitted.)     private void cmdPrint_Click(object sender, System.EventArgs e) {              // Create the document and attach an event handler.         PrintDocument doc = new PrintDocument();         doc.PrintPage += new PrintPageEventHandler(this.Doc_PrintPage);         // Allow the user to choose a printer and specify other settings.         PrintDialog dlgSettings = new PrintDialog();         dlgSettings.Document = doc;         // If the user clicked OK, print the document.         if (dlgSettings.ShowDialog() == DialogResult.OK) {                      // This method returns immediately, before the print job starts.             // The PrintPage event will fire asynchronously.             doc.Print();         }     }     private void Doc_PrintPage(object sender, PrintPageEventArgs e) {              // Define the font.         Font font = new Font("Arial", 30);         // Determine the position on the page.         // In this case, we read the margin settings         // (although there is nothing that prevents your code         // from going outside the margin bounds.)         float x = e.MarginBounds.Left;         float y = e.MarginBounds.Top;         // Determine the height of a line (based on the font used).         float lineHeight = font.GetHeight(e.Graphics);         // Print five lines of text.         for (int i=0; i < 5; i++) {                      // Draw the text with a black brush,             // using the font and coordinates we have determined.             e.Graphics.DrawString("This is line " + i.ToString(),                font, Brushes.Black, x, y);             // Move down the equivalent spacing of one line.             y += lineHeight;         }         y += lineHeight;         // Draw an image.         e.Graphics.DrawImage(Image.FromFile(Application.StartupPath +            "\test.bmp"), x, y);     } } 

This example has one limitation: it can only print a single page. To print more complex documents and span multiple pages, you will probably want to create a specialized class that encapsulates the document information, the current page, and so on. This technique is demonstrated in recipe 8.14.




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

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