I'm trying to split a very long string (document) on several pages containing a TextBlock, however, I need to make each page of specific number of lines which means that I need to split the TextBlock into lines.
I tried to create several logics but no luck of getting an accurate thing, but found a solution here (Get the lines of the TextBlock according to the TextWrapping property?) which worked for me on my prototype project then stopped working and gets the whole text in one line.
Here is the code from the above topic:
public static class TextUtils
{
public static IEnumerable<string> GetLines(this TextBlock source)
{
var text = source.Text;
int offset = 0;
TextPointer lineStart = source.ContentStart.GetPositionAtOffset(1, LogicalDirection.Forward);
do
{
TextPointer lineEnd = lineStart != null ? lineStart.GetLineStartPosition(1) : null;
int length = lineEnd != null ? lineStart.GetOffsetToPosition(lineEnd) : text.Length - offset;
yield return text.Substring(offset, length);
offset += length;
lineStart = lineEnd;
}
while (lineStart != null);
}
}
And this is my code:
<TextBlock x:Name="testTB" TextAlignment="Justify" FontFamily="Arial" FontSize="12" TextWrapping="Wrap" Width="100"/>
testTB.Text = Functions.GenString(200);
foreach (string xc in testTB.GetLines())
{
MessageBox.Show(xc);
}
Where I guess that the issue is that lineStart.GetLineStartPosition(1)
is returning null.
Any help is appreciated, thanks in advance.