Click here to Skip to main content
15,867,316 members
Articles / Programming Languages / C++
Article

Printing without the Document/View framework

Rate me:
Please Sign up or sign in to vote.
4.69/5 (41 votes)
29 May 2002CPOL1 min read 363.2K   130   85
Shows how to print without relying on the MFC Doc/View framework

Introduction

If you have a dialog based application and want to print, then you cannot take advantage of the Doc/View framework that MFC provides to do all the dirty work for you. The code presented below demonstrates the typical steps needed to:

  • prompt the user for the printing characteristics such as printer and paper size (via a call to CPrintDialog::DoModal)
  • Setup a printer DC and printing DOCINFO structure
  • Use callbacks to adjust settings such as start and end pages to print, or printing sizes
  • Print all pages to be printed
  • Cleanup

The callbacks

In order to keep the MFC Doc/View feel I recomend providing helper callback functions OnBeginPrinting, OnEndPrinting and OnPrint similar to the CView versions. A CDC and a CPrintInfo object is passed into each of these functions. You will have to provide these functions yourself. Typically you would undertake any initialisation neessary (such as creating GDI objects) in OnBeginPrinting. Your OnPrint function would be where you do the actual printing/drawing, and your OnEndPrinting function performs any cleanup necessary (such as deleting GDI objects created in OnBeginPrinting). You can call these functions whatever you want - I've used these names to be consistant with the CView names, and they are only used to show where the various initialisation/printing/cleanup code should be inserted by you.

Typical implementations would look like:

void OnBeginPrinting(CDC *pDC, CPrintInfo* pInfo)
{
    // maybe pre cache some pens or brushes, or modify the
    // properties of the DC
}

void OnPrint(CDC *pDC, CPrintInfo* pInfo)
{
    // Do your drawing/printing exactly as you would in a
    // CView::OnDraw function. The CPrintInfo structure
    // will give you the bounds and the current page number
}

void OnEndPrinting(CDC *pDC, CPrintInfo* pInfo)
{
    // Clean up pens or brushes, or restore the DC
}

The Printing code

void CMyDialog::Print() 
{
    CDC dc;
    CPrintDialog printDlg(FALSE);

    if (printDlg.DoModal() == IDCANCEL)     // Get printer settings from user
        return;

    dc.Attach(printDlg.GetPrinterDC());     // Get and attach a printer DC
    dc.m_bPrinting = TRUE;

    CString strTitle;                       // Get the application title
    strTitle.LoadString(AFX_IDS_APP_TITLE);

    DOCINFO di;                             // Initialise print document details
    ::ZeroMemory (&di, sizeof (DOCINFO));
    di.cbSize = sizeof (DOCINFO);
    di.lpszDocName = strTitle;

    BOOL bPrintingOK = dc.StartDoc(&di);    // Begin a new print job

    // Get the printing extents and store in the m_rectDraw field of a 
    // CPrintInfo object
    CPrintInfo Info;
    Info.m_rectDraw.SetRect(0,0, 
                            dc.GetDeviceCaps(HORZRES), 
                            dc.GetDeviceCaps(VERTRES));

    OnBeginPrinting(&dc, &Info);            // Call your "Init printing" function
    for (UINT page = Info.GetMinPage(); 
         page <= Info.GetMaxPage() && bPrintingOK; 
         page++)
    {
        dc.StartPage();                     // begin new page
        Info.m_nCurPage = page;
        OnPrint(&dc, &Info);                // Call your "Print page" function
        bPrintingOK = (dc.EndPage() > 0);   // end page
    }
    OnEndPrinting(&dc, &Info);              // Call your "Clean up" function

    if (bPrintingOK)
        dc.EndDoc();                        // end a print job
    else
        dc.AbortDoc();                      // abort job.

    dc.DeleteDC();                          // delete the printer DC
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder CodeProject
Canada Canada
Chris Maunder is the co-founder of CodeProject and ContentLab.com, and has been a prominent figure in the software development community for nearly 30 years. Hailing from Australia, Chris has a background in Mathematics, Astrophysics, Environmental Engineering and Defence Research. His programming endeavours span everything from FORTRAN on Super Computers, C++/MFC on Windows, through to to high-load .NET web applications and Python AI applications on everything from macOS to a Raspberry Pi. Chris is a full-stack developer who is as comfortable with SQL as he is with CSS.

In the late 1990s, he and his business partner David Cunningham recognized the need for a platform that would facilitate knowledge-sharing among developers, leading to the establishment of CodeProject.com in 1999. Chris's expertise in programming and his passion for fostering a collaborative environment have played a pivotal role in the success of CodeProject.com. Over the years, the website has grown into a vibrant community where programmers worldwide can connect, exchange ideas, and find solutions to coding challenges. Chris is a prolific contributor to the developer community through his articles and tutorials, and his latest passion project, CodeProject.AI.

In addition to his work with CodeProject.com, Chris co-founded ContentLab and DeveloperMedia, two projects focussed on helping companies make their Software Projects a success. Chris's roles included Product Development, Content Creation, Client Satisfaction and Systems Automation.

Comments and Discussions

 
QuestionPrinting without the Document/View framework Pin
kimba1111-Sep-12 6:41
kimba1111-Sep-12 6:41 
GeneralTerrific! Pin
Mike Gaskey6-Dec-11 9:49
Mike Gaskey6-Dec-11 9:49 
GeneralRe: Terrific! Pin
Chris Maunder6-Dec-11 9:50
cofounderChris Maunder6-Dec-11 9:50 
Talk about a blast from the past!
cheers,
Chris Maunder

The Code Project | Co-founder
Microsoft C++ MVP

Generalmemory leak Pin
lichongbin7-Mar-11 22:56
lichongbin7-Mar-11 22:56 
QuestionHow should i use this way to print a Recordset ? Pin
HappyErato26-Nov-09 21:06
HappyErato26-Nov-09 21:06 
QuestionHow to programmatically make the printing fail through OnPrint Pin
el davo25-Aug-08 17:18
el davo25-Aug-08 17:18 
Questionwhat is AFX_IDS_APP_TITLE? Pin
kamal21-Nov-06 22:39
kamal21-Nov-06 22:39 
AnswerRe: what is AFX_IDS_APP_TITLE? Pin
S Douglas28-Nov-06 23:07
professionalS Douglas28-Nov-06 23:07 
GeneralRe: what is AFX_IDS_APP_TITLE? Pin
kamal29-Nov-06 22:50
kamal29-Nov-06 22:50 
GeneralRe: what is AFX_IDS_APP_TITLE? Pin
S Douglas30-Nov-06 4:05
professionalS Douglas30-Nov-06 4:05 
Generalthanks a lot! Pin
kamal6-Dec-06 18:30
kamal6-Dec-06 18:30 
GeneralRe: thanks a lot! Pin
S Douglas7-Dec-06 6:19
professionalS Douglas7-Dec-06 6:19 
QuestionExcellent One!! A small question... Pin
kvrnkiran9-Oct-06 20:05
kvrnkiran9-Oct-06 20:05 
GeneralPrinting a CRichEditView from a CWinThread Pin
almc4-Jan-06 9:53
almc4-Jan-06 9:53 
QuestionPrinting without the Document / View Framework Pin
BuckBrown25-Oct-05 14:27
BuckBrown25-Oct-05 14:27 
GeneralDifferences between CDC::StartPage()/CDC::EndPage() and StartPagePrinter()/EndPagePrinter() Pin
RYU^^3-May-05 15:02
RYU^^3-May-05 15:02 
GeneralPreview Pin
Zoltan17-Apr-05 6:30
Zoltan17-Apr-05 6:30 
GeneralSomeone Has To Know How To Do This! Pin
rrrtek3-Mar-05 18:12
rrrtek3-Mar-05 18:12 
GeneralRe: Someone Has To Know How To Do This! Pin
RYU^^3-May-05 17:29
RYU^^3-May-05 17:29 
GeneralChanging the page size. Pin
rtek1-Mar-05 12:23
rtek1-Mar-05 12:23 
GeneralDC problem Pin
situ10-Jan-05 8:37
situ10-Jan-05 8:37 
QuestionHow can I select type of paper or number of copies ? Pin
Walote (630304)13-Oct-04 10:13
Walote (630304)13-Oct-04 10:13 
GeneralErrors in article 'Printing without the Document/View framework' Pin
Luka Lednicki23-Jul-04 7:50
Luka Lednicki23-Jul-04 7:50 
Questionscrollview printing?? Pin
xxhimanshu28-Jun-04 17:59
xxhimanshu28-Jun-04 17:59 
GeneralPrinting without Print Dialog box Pin
sakthisaravanan28-Jun-04 0:47
sakthisaravanan28-Jun-04 0:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.