Printing with MFC

Using the MFC standard document/view architecture, a single "view" is printed at a time. The mechanism can be summarised by the following diagram (from the MSDN article "Printing: Multipage Documents"):

This mechanism need not be followed exactly if there are different printing requirements. An alternative mechanism is now described. First you need to get a Device Context for the printer, by either of the following methods:

  1. Display the standard Windows print dialogue, either by calling the Windows API function PrintDlg, or the MFC function CView::DoPreparePrinting. The print dialogue can return a Device Context for the printer that the user selected.
  2. Obtain a list of printers by calling the Windows API function EnumPrinters(PRINTER_ENUM_NAME, NULL, 2, …) to return an array of PRINTER_INFO_2 structures, one per available printer. Select the required printer, and create a Device Context for it by calling CDC::CreateDC(pszDriverName, pszPrinterName, NULL, NULL) with the strings from the required PRINTER_INFO_2 structure.

Set the CDC::m_bPrinting flag to TRUE, to allow drawing routines to query whether the drawing is to the screen or to the printer by calling CDC:IsPrinting.

Create a DOCINFO structure describing the "document" to be printed, and pass it to CDC::StartDoc to start printing the document.

For each page in the output, first call CDC::StartPage. The Device Context will now refer to a single page in the printed output. Use this Device Context to draw each element of the printed output, for example by calling the CView::OnDraw or CView::OnPrint function for each displayed window. The logical co-ordinates used for drawing can be scaled and offset as required for each window, to position each window’s output in the appropriate place on the printed page. The Device Context scaling and offset can be modified either before passing it to each window, or by the window’s drawing routine itself (by calling CDC:IsPrinting to determine that the window is drawing to a printed page rather than the screen). Once the page is complete, call CDC::EndPage, and repeat for the following page (if necessary).

Finally, call CDC::EndDoc to close the document, which will then actually be spooled to the printer.