I have a partial solution to this as shown below. It works for me but I have had a few problems where the table and/or Cell concerned has Borders defined (please feel free to correct/adjust
)
I use this when I am contructing a table cell and inserting the text. Therefore in advance I know the Cell object and the Font which I will be rendering with
Code:
var style = document.Styles["Normal"];
style.Font.Size = 5.0;
tm = new TextMeasurement(document.Styles["Normal"].Font.Clone());
I then add the text to the cell as follows
Code:
string someText = "I like to eat at McGruderalpostermus.";
cell.AddParagraph(AdjustIfTooWideToFitIn(cell, someText));
and the code that peforms the width adjustment is as follows
Code:
private static string AdjustIfTooWideToFitIn(Cell cell, string text)
{
Column column = cell.Column;
Unit availableWidth = column.Width - column.Table.Borders.Width - cell.Borders.Width;
var tooWideWords = text.Split(" ".ToCharArray()).Distinct().Where(s => TooWide(s, availableWidth));
var adjusted = new StringBuilder(text);
foreach (string word in tooWideWords)
{
var replacementWord = MakeFit(word, availableWidth);
adjusted.Replace(word, replacementWord);
}
return adjusted.ToString();
}
private static bool TooWide(string word, Unit width)
{
float f = tm.MeasureString(word, UnitType.Point).Width;
return f > width.Point;
}
/// <summary>
/// Makes the supplied word fit into the available width
/// </summary>
/// <returns>modified version of the word with inserted Returns at appropriate points</returns>
private static string MakeFit(string word, Unit width)
{
var adjustedWord = new StringBuilder();
var current = string.Empty;
foreach (char c in word)
{
if (TooWide(current + c, width))
{
adjustedWord.Append(current);
adjustedWord.Append(Chars.CR);
current = c.ToString();
}
else
{
current += c;
}
}
adjustedWord.Append(current);
return adjustedWord.ToString();
}
Here is an example of the above in use
Attachment:
File comment: Example of word adjustment in column 3. Column 1 shows the unadulterated text
CellWidthAdjust.JPG [ 7.63 KiB | Viewed 16940 times ]