Question
“How can I append a ‘…’ to the end of text that is too wide to fit the bounds of a control?”
Solution
ReportBuilder 12 introduced the TppCustomText.Ellipsis property to automatically truncate text too wide to fit in a given area. Below is an example of performing this task for versions earlier than RB 12.
—
The following example shows how to calculate the width of text and truncate it with a ‘…’ when the text is too wide to fit.
Download: FormatTextWithEllipse.zip
uses
ppUtils,
ppTypes;
procedure TForm1.ppDetailBand1BeforePrint(Sender: TObject);
var
lsText: String;
begin
lsText := ppReport1.DataPipeline['Company'];
ppLabel1.Caption := FormatTextWithEllipse(ppLabel1, lsText);
end;
function TForm1.FormatTextWithEllipse(aLabel: TppLabel; aText: string): string;
const
csEllipses = '...';
var
ldTextWidth: Double;
lsText: String;
begin
Result := aText;
lsText := aText;
ldTextWidth := CalcTextWidthInReportUnits(lsText, aLabel.Font);
{shrink length of text and add the elipses, as needed}
if (ldTextWidth > ppLabel1.Width) then
repeat
lsText := Copy(lsText,1, Length(lsText)-1);
Result := lsText + csEllipses;
ldTextWidth := CalcTextWidthInReportUnits(Result, aLabel.Font);
until (ldTextWidth < ppLabel1.Width);
end;
function TForm1.CalcTextWidthInReportUnits(aText: String; aFont: TFont): Double;
var
liPrinterPixels: Integer;
liMicrons: Integer;
begin
ppReport1.Printer.Canvas.Font := aFont;
{calc width in printer pixels}
liPrinterPixels := ppReport1.Printer.Canvas.TextWidth(aText);
{convert to microns}
liMicrons := ppToMMThousandths(liPrinterPixels, utPrinterPixels, pprtHorizontal, ppReport1.Printer);
{convert from microns to report units}
Result := ppFromMMThousandths(liMicrons, ppReport1.Units, pprtHorizontal, ppReport1.Printer);
end;