|
PDFsharp Multiline MeasureString |
|
|
|
In the PDFsharp API it is not possible to measure the height and width of a string, given that the string must be broken into lines to fit into a layout rectangle. This method shows one workaround. It gives the basic idea, and works very reliably where we used it, but it has some limitations, for instance that it ignores the maximum height given in the arguments and just reports the actual height for the full string.
MeasureString can measure a string on one line, so this is leveraged to get the more advanced MeasureString, shown below.
private XSize MeasureString(string s, XGraphics g, XFont f, XStringFormat format, XSize maxSize)
{
string[] words = s.Split(new char[] {' '}); // split sentence into words by using spaces as delimiters
int lineCount = 1; // start on first line
double x = 0; // start at start of line
string line = "";
for (int wordIndex = 0; wordIndex < words.Length; wordIndex++)
{
string candidateLine = line + words[wordIndex] + " ";
// see whether the candidate fits onto a line
XSize lineSize = g.MeasureString(candidateLine, f, format);
if (lineSize.Width > maxSize.Width)
{
// it does not fit, so put it at the start of next line
Debug.WriteLine(line);
lineCount++;
line = words[wordIndex] + " ";
}
else
{
// it does fit, so the candidate line becomes the new line
line = candidateLine;
}
// in either case the word has been placed so it is incremented in for loop
}
Debug.WriteLine(line);
double height = lineCount * f.Height;
return new XSize(maxSize.Width, height);
}
|