Printing a text buffer

A lot of people have been asking questions about printing a simple straight multi-page text buffer to a user-selected printer, without using the docView framework. You could use the classes created by Richard Stringer, but quite often, this is a big overkill for what you want to do. A few suggestions have been made and Chris Maunder provided some samples on how to start with it. But no one gave a real world example. So I puzzled around abit, and finally came up with the code below.

It is far from perfect, and some additional function parameters would be cool. I will make a more advanced version when I find the time.

There is one major drawback to the method below : to find page breaks, it will start at the beginning of the buffer, and calculate the height needed for 1 character, 2 characters, 3 characters, ... and so on. When the height grows beyond the page size, a new page must be started with the previous character that didn't overflow yet. This method will have to call DrawText() for each character. A big calculation peak will be induced ! It would be a lot better to use entire words instead of characters. I intend to make such a version in the next few weeks.

Even better would be to use some statistics scheme and 'guess' where the page break will occur. Then jump back or forward with consecutively smaller blocks until you find the exact pagebreak location. (somewhat like the quicksort sorting algorithm) that's a problem for later. The routine works as it does now, and I hope someone can use it.


// p points to the start of the buffer, pSize holds the number of characters
void PrintString(char *p, DWORD pSize)
{
    CDC             dc;
    CPrintDialog    printDlg(FALSE);
    CRect           r;
    int             nHeight;
    
    // ask the user to select a printer
    if (printDlg.DoModal() == IDCANCEL)
        return;
    
    // Attach a printer DC
    dc.Attach(printDlg.GetPrinterDC());
    dc.m_bPrinting = TRUE;

    // use Textmappingmode, that's easiest to map the fontsize
    dc.SetMapMode(MM_TEXT);
    
    // setup font specifics
    LOGFONT LogFont;
    
    CFont	aFont, *oldFont;
    
    LogFont.lfHeight = -MulDiv(10, GetDeviceCaps(dc, LOGPIXELSY), 72);
    LogFont.lfWidth = 0;
    LogFont.lfEscapement = 0;
    LogFont.lfOrientation = 0;
    LogFont.lfWeight = 0;
    LogFont.lfItalic = false;
    LogFont.lfUnderline = 0;
    LogFont.lfStrikeOut = 0;
    LogFont.lfCharSet = ANSI_CHARSET;
    LogFont.lfOutPrecision = OUT_TT_PRECIS;
    LogFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
    LogFont.lfQuality = DEFAULT_QUALITY;
    LogFont.lfPitchAndFamily = DEFAULT_PITCH | FF_SWISS;
    lstrcpy (LogFont.lfFaceName, "MS Sans Serif");
    dc.SetBkMode(OPAQUE);
    aFont.CreateFontIndirect ( &LogFont );
    // ok, we've build the font, now use it
    oldFont = dc.SelectObject( &aFont );        
        
    // Get the application title
    CString strTitle;
    strTitle.LoadString(AFX_IDS_APP_TITLE);
    
    // Initialise print document details
    
    DOCINFO di;
    ::ZeroMemory (di, sizeof (DOCINFO));
    di.cbSize = sizeof (DOCINFO);
    // application title appears in the spooler view
    di.lpszDocName = strTitle;
    
    // Begin a new print job
    BOOL bPrintingOK = dc.StartDoc( &di );
        
    // Get the printing extents and store in the m_rectDraw field of a 
    // CPrintInfo object
    CPrintInfo Info;
    int w = dc.GetDeviceCaps(HORZRES);
    int h = dc.GetDeviceCaps(VERTRES);
    Info.m_rectDraw.SetRect(0,0, w, h);
    
    char *startAt = p;
    int totalDone = 0;
    int lengthToGo = pSize;
    
    for (UINT page = Info.GetMinPage();
    bPrintingOK & totalDone < lengthToGo; page++)
    {
        // begin new page
        dc.StartPage();
        Info.m_nCurPage = page;
        
        // calc how much text fits on one page
        r = Info.m_rectDraw;
        r.bottom = r.top;
        int i = 0;
        while (r.bottom < Info.m_rectDraw.bottom & totalDone + i < lengthToGo)
        {
            r.right = Info.m_rectDraw.right;
            nHeight = dc.DrawText(startAt, i++, r, 
                DT_CALCRECT|DT_WORDBREAK|DT_NOCLIP|DT_EXPANDTABS);
        }
        // go one back to assure correct height
        if (r.bottom >= Info.m_rectDraw.bottom)
            i--;
        
        
        // print that text
        dc.DrawText(startAt, i, r, DT_WORDBREAK|DT_NOCLIP|DT_EXPANDTABS);
        
        // go to next page
        startAt += i;
        totalDone += i;
        
        // end page
        bPrintingOK = (dc.EndPage() > 0);
    }
    
    // end a print job
    if (bPrintingOK)
        dc.EndDoc();
    else
        // abort job.
        dc.AbortDoc();
    
    
    // restore font
    dc.SelectObject(oldFont);
    // free font memory
    qFont.DeleteObject();
    // detach the printer DC
    dc.Detach();
}



Comments

  • Arbejde fantastisk ved monster beats

    Posted by wherewanzi on 06/05/2013 07:43pm

    [url=http://beatsbydrdredanmark.webstarts.com/]beats by dre danmark[/url] Beats By Dre blev født ud af et behov for at genoprette den følelsesmæssige forbindelse med musik, der gik tabt ved nedbrydning af lyden fra den digitale musik revolution, startende med det svageste led i oplevelsen ved time-hovedtelefoner, “sagde Beats President og COO , Luke Wood. “Men det var aldrig om bare hovedtelefoner. Vi har siden udvidet Beats mission til hver anden link i musikoplevelsen kæde – højttalere, mobiltelefoner, pc’er og bil lydsystemer. Med MOG, vi tilføjer den bedste musiktjeneste til Beats portefølje for den første ægte end-to-end musikoplevelse. Med deres talent og teknologi, er mulighederne omkring fremtidig innovation endeløs. [url=http://beatsbydrehretelefoner.weebly.com/]Beats by dre billig pris[/url] Ligegyldigt om nogen efterspørgsel en ny hookup vedrørende personlig ansætte i dit hus samt med henblik på at venstre arm din nuværende lille vedrørende institution, dette er den meget specielle, der vil sikre en favorit BIII øretelefoner spørgende, Min ægtefælle og jeg gravede lidt dybere involveret med det sammen med min ægtefælle og jeg, din ml i allexpect en ny, netop hvad jeg lige kigger ind nedenfor besøgende i de mange standard fornødenheder. Sandheden er, jeg er bare planlægning for dig at adskille idéen sammen i dit tilfælde for at sige det kort sort. [url=http://beatsbydrdredanmark.moonfruit.com/]beats by dre danmark[/url] Projektet kan opnås på en måde at bruge god til handling og magt lav overflod, og værdiskabende tilbehør. Den faktiske headset komfort element er virkelig stor. Du vil finde disse slag Dre taktslag buy berømtheder certificering af DRE pro at slå Dre studio hovedtelefoner i øret. BIII komme med en rengøringsklud til at sikre, at de er på udkig efter. For nylig fandt jeg en fælles ven kørte vej sat på afDr. Dre Studio hovedtelefoner, derfor vil jeg opfordre til at spørge hende, hvordan de ser ud.

    Reply
  • Nike Wind Max+instagram, will you confine the color to wear on your feet!

    Posted by madytreathy on 04/20/2013 06:16pm

    Remember in 2008, if not earlier, when Nike launched up ahead of the self-assured shoe color projects, the war cry "Bound Your Colours", "Nike PhotoiD" scheme, [url=http://northernroofing.co.uk/roofins.cfm]nike free run 3[/url] reply has not been as fervent as expected. Think, 2008 Canon IXUS 80 IS Digital card arcade but one 8 million pixels, Nokia, the motorized phone retail is the one governorship, NikeiD was promote to color in the photos as a underpinning in return sneakers levy color, although exciting, but does bother some. Instagram which communicate this article fun and modest, Nike PHOTOiD homeopathic upgrade customization services, recently [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache free[/url] released a fresh plan. That such iD can you utensil pictures as instagram account shoe color, temporarily offer Nike Aura Max shoes and Nike Refresh Max 1, Nike Air Max 90 953 options. Interested in children's shoes, you [url=http://markwarren.org.uk/goodbuy.cfm]nike free run uk[/url] can without exception conform with each other's legitimate website photoid.Nike.com, in reckoning to skim through other people's creative charge, or you can make an effort to upload your own instagram photo, physique your own Nike Hauteur Max.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • The explosion in mobile devices and applications has generated a great deal of interest in APIs. Today's businesses are under increased pressure to make it easy to build apps, supply tools to help developers work more quickly, and deploy operational analytics so they can track users, developers, application performance, and more. Apigee Edge provides comprehensive API delivery tools and both operational and business-level analytics in an integrated platform. It is available as on-premise software or through …

  • Not long ago, security was viewed as one of the biggest obstacles to widespread adoption of cloud-based deployments for enterprise software solutions. However, the combination of advancing technology and an increasing variety of threats that companies must guard against is rapidly turning the tide. Cloud vendors typically offer a much higher level of data center and virtual system security than most organizations can or will build out on their own. Read this white paper to learn the five ways that cloud …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds