public static float FitText(Font font, String text, Rectangle rect, float maxFontSize, int runDirection) {
ColumnText ct = null;
int status = 0;
if (maxFontSize <= 0) {
int cr = 0;
int lf = 0;
char[] t = text.ToCharArray();
for (int k = 0; k < t.Length; ++k) {
if (t[k] == '\n')
++lf;
else if (t[k] == '\r')
++cr;
}
int minLines = Math.Max(cr, lf) + 1;
maxFontSize = Math.Abs(rect.Height) / minLines - 0.001f;
}
font.Size = maxFontSize;
Phrase ph = new Phrase(text, font);
ct = new ColumnText(null);
ct.SetSimpleColumn(ph, rect.Left, rect.Bottom, rect.Right, rect.Top, maxFontSize, Element.ALIGN_LEFT);
ct.RunDirection = runDirection;
status = ct.Go(true);
if ((status & NO_MORE_TEXT) != 0)
return maxFontSize;
float precision = 0.1f;
float min = 0;
float max = maxFontSize;
float size = maxFontSize;
for (int k = 0; k < 50; ++k) { //just in case it doesn't converge
size = (min + max) / 2;
ct = new ColumnText(null);
font.Size = size;
ct.SetSimpleColumn(new Phrase(text, font), rect.Left, rect.Bottom, rect.Right, rect.Top, size, Element.ALIGN_LEFT);
ct.RunDirection = runDirection;
status = ct.Go(true);
if ((status & NO_MORE_TEXT) != 0) {
if (max - min < size * precision)
return size;
min = size;
}
else
max = size;
}
return size;
}