I'm trying to estimate the printed width of a run of text while creating a document, so that I can truncate the text to fit on a single line in a table cell.
I've managed to do this for specific situations using the following code:
Code:
private static string FitString(string value, Font font, float availableWidth)
{
var ruler = new TextMeasurement(font);
value = value.Trim();
SizeF size = ruler.MeasureString(value, UnitType.Point);
if (size.Width > availableWidth) value = value + "\u2026";
while (size.Width > availableWidth)
{
value = value.Substring(0, value.Length - 3).Trim() + "\u2026";
size = ruler.MeasureString(value, UnitType.Point);
}
return value;
}
However, I've found myself in a situation where I won't always know which
Font object to grab. For instance, because in previous usages I knew the structure and formatting of the document ahead of time, I knew that the
Cell I was truncating would use the
Table's font size and name, so I would just grab the
Font using something like
table.Format.Font.
For my current project, this is no longer the case; I'm trying to generalize my
FitString function so that I use it at a higher level, where I can't assume anything about the location of the formatting information.
Is there any way to easily figure out what formatting properties will ultimately be applied to a
DocumentObject, or at least a
Cell in particular?