Friday, September 9, 2011

Printing images with wxWidgets

Printing an image, mixed with text, is a common requirement. Just think of printing a customer's logo on an invoice.

Printing an image at a given size in wxWidgets has been a rather difficult task, mainly for the lack of documentation or examples. After some trial and error I found a working solution and I will describe it here. This solution is based on what I described for printing text. You will need to read that post too.

1 - Load the image in a wxImage object, resize it, convert it to a wxBitmap. You need to resize the image so that you can print it pixel by pixel and obtain a printed image of the desired size. To define the image size you need to know the desired printed size or the image DPI. You can know the printer's resolution using wxDC::GetPPI().
Starting from the original image size and the printer's resolution you can compute the new image size and rescale it.
If you know the image's DPI you can compute the new image size in pixels using this formula:
newWidth_pixels = printerPPI / imageDPI * originalWidth_pixels

If you know the printed image's width (in mm) that you want to obtain you can compute the new image size in pixels using this formula:
newWidth_pixels =  printedWidth_mm * PPI / 25.4

2 - Print the bitmap, making sure that wxWidgets does not resize it. This is the difficult part, since I ended up with a much larger image than what I wanted. The problem is that I set up a user scale with wxDC::SetUserScale() and that scale was also applied to the image, enlarging it. The solution is, obviously, to set the user scale to 1 before drawing the bitmap. Here is a function that I use for the purpose (x and y are the print coordinates in mm):

void PrintBitmap( wxDC *dc, const float logUnitsFactor, wxBitmap &bitmap, const float x, const float y )
{
        double xScale, yScale;
        dc->GetUserScale( &xScale, &yScale );
        dc->SetUserScale( 1, 1 );
        dc->DrawBitmap( bitmap, x*logUnitsFactor*xScale, y*logUnitsFactor*yScale, true );
        dc->SetUserScale( xScale, yScale );
}

No comments:

Post a Comment