Tuesday, March 8, 2011

Printing text with wxWidgets II

Printing to the default printer

A common requirement is printing directly to the default printer, without showing any printer selection dialog.
Referring to the code of the previous post this can be accomplished by changing one line of code from

bool success = printer.Print( NULL, &printout, true );

to

bool success = printer.Print( NULL, &printout, false );

According to the documentation this should work, but the code (at the moment of writing this post) does not print anything.
Some debugging shows that there is a bug in the wxWidgets code: the bug will be fixed, but at the moment the problem can be solved adding one line of code.
So working code looks like the this:

wxPrintDialogData printDialogData(* m_PrintData);
printDialogData.SetToPage( printDialogData.GetMaxPage() );
wxPrinter printer( &printDialogData );
bool success = printer.Print( NULL, &printout, true );


Setting the To page to the Max page fixes the problem.

Centering text (and similar)

Another common requirement is comparing the width of some text to the width of the page, for example to center the text, but it is not very clear how to obtain the desired sizes in the same units, so that they can be compared in a correct way.

The previous post shows how to compute a variable (logUnitsFactor) to convert from millimeters to logical units.
The page size in millimeters can be obtained by calling wxPrintout::GetPageSizeMM(), then the size in millimeters can be converted to logical units multiplying it by logUnitsFactor.

The width of a text can be obtained calling wxDC::GetTextExtent(): the result is in logical units that can be compared to the previously computed page width.
For example (code inside a wxPrintout-derived object):

    // compute the available width in logical units
    int pageWidthMM, pageHeightMM;
    GetPageSizeMM(&pageWidthMM, &pageHeightMM);
    int availableWidth = (pageWidthMM - m_MarginLeft - m_MarginRight)*logUnitsFactor;
    wxCoord ew, eh;
    dc->GetTextExtent( "Some text", &ew, &eh, NULL, NULL );
    // now we can compare "ew" and "availableWidth"

1 comment:

  1. I read this article. I think You put a lot of effort to create this article. I appreciate your work. sticker printing

    ReplyDelete