TextOut to the center of Device Context

Viewed 273

It frustrates me how difficult this is for me to figure out. I have an MFC application with a print feature. When I hit print I want to create a pdf file with a single word in the center of the A4 page. I am using a CPrintDialog and I actually managed to obtain my result on my machine (by hardcoding the coordinates for TextOut).

I want this software to work on any type of device context. My guess is that there has to be a way to get the logical coordinates (which TextOut expects) out of the CDC. I was playing around with GetDeviceCaps (with HORZSIZE, HORZRES, LOGPIXELSX, ASPECTX, PHYSICALWIDTH) but none of these values even gets close to my hardcoded values. The fact that the y coordinate I use is a negative value baffles me even more. Is there a generic way to find the center of the device context?

Here are the values I see:

const int logPixY = dcPrinter.GetDeviceCaps(LOGPIXELSY); //600
const int logPixX = dcPrinter.GetDeviceCaps(LOGPIXELSX); //600

const int horzSize = dcPrinter.GetDeviceCaps(HORZSIZE);  //216
const int vertSize = dcPrinter.GetDeviceCaps(VERTSIZE);  //279

const int horzRez = dcPrinter.GetDeviceCaps(HORZRES);    //5100
const int vertRez = dcPrinter.GetDeviceCaps(VERTRES);    //6600

const int pWidth  = dcPrinter.GetDeviceCaps(PHYSICALWIDTH); //5100
const int pHeight = dcPrinter.GetDeviceCaps(PHYSICALHEIGHT);//6600

const int aspectX = dcPrinter.GetDeviceCaps(ASPECTX);    //600
const int aspectY = dcPrinter.GetDeviceCaps(ASPECTY);    //600

And the hardcoded DrawText that writes at the center of the page (kind of) is:

dcPrinter.TextOut(4200, -5000, L"Center");
1 Answers

If using GDI it would be far easier to do centering via

SetTextAlign(hdc, TA_VCENTER|TA_VCENTER);

then simply use the page's center point (width/2, height/2) as the TextOut reference point. Let the TextOut API do the work of calculating the text's display area.

Related