I did not test it extensively, but it seems that it gave the correct results. The result is the width of the text in a thousandth of a millimeter. This feature does not support word wrap and other special considerations.
Also note that when working with the printer, incorrect print registration can “stretch” the text.
Also note that for a printer, changing, for example, print resolution from 300 ppp to 1200 ppp will also change the result.
uses
ConvUtils, stdConvs ;
function CalcRequiredTextWidth(aDC : HDC; aFont : TFont; const asText: string): Double;
var vCanvas : TCanvas;
iPixelsWidth : Integer;
dInchWidth : Double;
iFontSize : Integer;
begin
vCanvas := TCanvas.Create;
try
vCanvas.Handle := aDC;
vCanvas.Font.Assign(aFont);
iFontSize := vCanvas.Font.Size;
vCanvas.Font.PixelsPerInch := GetDeviceCaps(aDC, LOGPIXELSY);
vCanvas.Font.Size := iFontSize;
iPixelsWidth := vCanvas.TextExtent(asText).cx;
dInchWidth := iPixelsWidth / GetDeviceCaps(vCanvas.Handle, LOGPIXELSX);
Result := Convert(dInchWidth, duInches, duMicrons);
finally
vCanvas.Free;
end;
end;
source
share