Click here to Skip to main content
Click here to Skip to main content

A Simple Printing Mechanism

By , 16 May 2000
 
  • Download source files - 6 Kb

    A question that frequently arises is "How do I print?" In many cases, the full-blown print handling of a document/view class is inappropriate; in other cases, such as a dialog-based application, it is not available directly via the MFC library. This little class provides for some simple line-printer-simulation output, suitable for printing files, simple text, etc. This is the print mechanism I use for my logging control (and the code for this accompanies that project as well).

    void CMyClass::Print()
    {
        CPrintDialog dlg(FALSE,
    		      PD_ALLPAGES |
    		      PD_HIDEPRINTTOFILE |
    		      PD_NOPAGENUMS |
    		      PD_RETURNDC |
    		      PD_USEDEVMODECOPIES);
        if(has a selection)
    	{ /* enable selection */
            dlg.m_pd.Flags |= PD_SELECTION;
        } /* enable selection */
        else
        { /* use selection */
            dlg.m_pd.Flags |= PD_NOSELECTION;
        } /* use selection */
        
        switch(dlg.DoModal())
        { /* DoModal */
        case 0:
        case IDCANCEL:
            return;
        case IDOK:
            break;
        default:
            ASSERT(FALSE); // impossible condition
            return;
        } /* DoModal */
         
        CDC dc;
        dc.Attach(dlg.m_pd.hDC);
        printer = new CPrinter(&dc);
        if(printer->StartPrinting())
        { /* success */
            for(some sample loop condition)
            { /* print line */
                CString s;
                ... // form the string you want to print
                printer->PrintLine(s);
            } /* print line */
    
            printer->EndPrinting();
        } /* success */
        delete printer;
        ::DeleteDC(dc.Detach());
    } // CTraceList::Print
    

    This is listed as a simple printing mechanism. It is not as elaborate as the one in our book Win32 Programming., but that is a pure-C version. This is a simpler, but pure MFC, example.

    You can download just this printing code here, or you can download it as part of the Logging Control project.


    CPrinter

    CPrinter::CPrinter(CDC * dc)
    Constructs a printer object with the DC of a printer. This is typically obtained from the CPrintDialog by using the flag PD_RETURNDC, then using CDC::FromHandle to get an MFC object for the DC.

    CPrinter::EndPrinting()
    This terminates the print job. It calls the necessary EndPage and EndDoc functions. If the CPrinter object is destroyed while a print job is active, the destructor will call this method.

    int CPrinter::GetPageNumber()
    This function can be called by a subclass's PageHeading routine to get the current page number.

    virtual void CPrinter::PageHeading()
    This method can be overridden in a subclass to print a page heading. The default effect in the base class is to print the program name on the left and the page number on the right.

    void CPrinter::PrintLine(const CString & line)
    This method prints a single line to the printer. No attempt is made to do line wrapping. Implicit left and top margins are assumed. If the line would overflow the existing printable page area, the current page is terminated and a new page is started. The page number is incremented, and heading is printed on the new page (see CPrinter::PageHeading()).

    virtual void CPrinter::SetPrinterFont()
    In the base class, this establishes the printer font as the stock ANSI_FIXED_FONT. A subclass may override this to provide its own font.

    CPrinter::StartPrinting()
    Starts a document on the printer. This must be called before any PrintLine calls are made. This sets up default margins and performs the necessary ::StartDoc call.


    The views expressed in these essays are those of the author, and in no way represent, nor are they endorsed by, Microsoft.

    Send mail to newcomer@flounder.com with questions or comments about this article.
    Copyright © 2000, The Joseph M. Newcomer Co. All Rights Reserved
    www.flounder.com/mvp_tips.htm
  • License

    This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

    A list of licenses authors might use can be found here

    About the Author

    Joseph M. Newcomer
    United States United States
    Member
    No Biography provided

    Sign Up to vote   Poor Excellent
    Add a reason or comment to your vote: x
    Votes of 3 or less require a comment

    Comments and Discussions

     
    You must Sign In to use this message board.
    Search this forum  
        Spacing  Noise  Layout  Per page   
    QuestionPrinting Problummemberlcloonkar10 Jan '10 - 4:15 
    My Epson LX 300 Printer Print Only in Right Side How to Solve The Problum Smile | :) Smile | :)
    Questionwhen printer is not configured?member723Alex20 Jul '07 - 10:41 
    I use this Printer class successfully in my application. There one thing I need add and I don't know how. Sometimes when I start printing from the application the network printer is not configured or is disconnected. Looks like the printing code does not see it and goes through without errors. Is there any way to detect in code that printer is unavailable and inform the user.
    Thanks.
    GeneralMFC Print preview problemmemberEngineer Masood30 Mar '06 - 16:52 
    hi all
    In SDI application i am drawing graphics
    by using lines the problem is that print
    preview and print output is small image
    not actuall image size. can any one provide
    code to fx the problem.
    GeneralTnxmemberquistiun8 Mar '06 - 18:26 
    tnx for your work....
     
    quistiun
    GeneralProblem found in StartPrintingmemberapargeter24 Sep '05 - 9:14 
    One of the info fields (cbSize) is not initialized.
     
    BOOL CPrinter::StartPrinting()
    {
    DOCINFO info;
    ::ZeroMemory(&info, sizeof(info));
    info.cbSize = sizeof(DOCINFO); //<---ADD THIS LINE!
    info.lpszDocName = AfxGetAppName();
     
    SetPrinterFont();
     
    dc->StartDoc(&info);
    docStarted = TRUE;
     
    TEXTMETRIC tm;
    dc->GetTextMetrics(&tm);
    lineHeight = tm.tmHeight + tm.tmInternalLeading;
    pageVMargin = dc->GetDeviceCaps(LOGPIXELSY) / 2;
    pageHMargin = dc->GetDeviceCaps(LOGPIXELSX) / 2;
    pageHeight = dc->GetDeviceCaps(VERTRES);
    pageWidth = dc->GetDeviceCaps(HORZRES);
    Y = pageVMargin;
    return TRUE;
    } // CPrinter::StartPrinting
     

    GeneralProblem when Print Arabic fontsmemberbushka12 Jun '05 - 11:25 
    When I use arabic font in Visual C++, it appear correct in view but in printpreview window arabic characters overlaped to each other. I use This statement
     
    CFont ffont;
    ffont.CreateFont(-18,0,0,0,700,0,0,0,178,3,2,1,2,"Arial");
     
    mapmode is MM_LOENGLISH
     
    I need help. Any body have the solution pleas send to my email
    thanks
    GeneralRe: Problem when Print Arabic fontsmemberJoseph M. Newcomer12 Jun '05 - 17:11 
    I can understand -18, 0, 0, 0, but what is 700? Oh, you meant FW_BOLD. 0, 0, 0 you probably meant FALSE, FALSE, FALSE. What the hell is 178? 3? 2? 1? 2? Those numbers are completely meaningless! Perhaps by 178 you meant ARABIC_CHARSET? If so, why didn't you write that? And I haven't a clue as to what those other numbers could possibly mean. The code may or may not be correct, but I have no idea if it is or not.
     
    When the code is written intelligibly, I might have a fraction of chance of guessing what is wrong. Or maybe not. But something this unintelligible is not something I would even offer an opinion on. Note that once it is rewritten, I may not see anything wrong, but I can't tell anything from such a piece of incorrect code.
    GeneralRe: Problem when Print Arabic fontssussAnonymous13 Jun '05 - 5:54 
    From : Bushka
    to : Mr.Joseph M. Newcomer
    Very Thanks to email me and I'm sorry for numbers in function CreateFont this mean the number
    CreateFont( int nHeight, int nWidth, int nEscapement, int nOrientation, int nWeight, BYTE bItalic, BYTE bUnderline, BYTE cStrikeOut, BYTE nCharSet, BYTE nOutPrecision, BYTE nClipPrecision, BYTE nQuality, BYTE nPitchAndFamily, LPCTSTR lpszFacename );
     
    You can find more detail in MSDN and for the number 178 this ARABIC_CHARSET
     
    My problem in PrintView with arabic only, English no problem with it. printing like view with no any problem.
     
    Also I use only function OnDraw
     
    thanks again and i hope to find answer
     
    I can send the source code but where ???

     
    I use number
    GeneralPrinting files from VB/VCmemberfranklinjIssac4 Apr '05 - 1:50 
    Hi,
    I need some help in doing my current task involving printing. The requirement is to listen in a paricular folder and ANY files coming to that folder has be sent to a default network printer, after taking note of the pagecount of that file.I tried with a dummy printer connection. It worked.But,when taking it to a real printer, the "GetPrinter" function is not returning the actual job count.
    The simple function i used to print is "ShellExecute" with "print" as the operation parameter.
     
    Regards,
    Franklin
    GeneralRe: Printing files from VB/VCmemberJoseph M. Newcomer4 Apr '05 - 10:25 
    I've never used GetPrinter; so I have no experience to suggest what might be happening.
    joe

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

    Permalink | Advertise | Privacy | Mobile
    Web04 | 2.6.130523.1 | Last Updated 17 May 2000
    Article Copyright 2000 by Joseph M. Newcomer
    Everything else Copyright © CodeProject, 1999-2013
    Terms of Use
    Layout: fixed | fluid