0

C# WPF,我有一个功能来检索文本flowdocumentreader

static string GetText(TextPointer textStart, TextPointer textEnd)
{
     StringBuilder output = new StringBuilder();
     TextPointer tp = textStart;
     while (tp != null && tp.CompareTo(textEnd) < 0)
     {
         if (tp.GetPointerContext(LogicalDirection.Forward) ==
         TextPointerContext.Text)
         {
             output.Append(tp.GetTextInRun(LogicalDirection.Forward));
         }
            tp = tp.GetNextContextPosition(LogicalDirection.Forward);
     }
    return output.ToString();
}

然后我使用如下功能:

 string test = GetText(rtb.Document.ContentStart, rtb.Document.ContentEnd);

但是,字符串"test"会忽略所有换行符,这意味着"\r\n". 它确实保留了制表符,"\t".

我的问题是如何保留所有换行符?我想自动突出显示每个段落的第一句,所以我需要检测换行符,"\r\n".

在此先感谢您的时间。

更新:我将 .rtf 文档加载到 flowdocumentreader 中,如下所示:

           if (dlg.FileName.LastIndexOf(".rtf") != -1)
            {
                paraBodyText.Inlines.Clear();
                string temp = File.ReadAllText(dlg.FileName, Encoding.UTF8);
                MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(temp));
                TextRange textRange = new TextRange(flow.ContentStart, flow.ContentEnd);

                textRange.Load(stream, DataFormats.Rtf);
                myDocumentReader.Document = flow;

                stream.Close();
            }
4

1 回答 1

0

已编辑

假设每个段落至少有一个以点结尾的句子,您可以使用以下代码将第一句加粗:

        List<TextRange> ranges = new List<TextRange>();
        foreach (Paragraph p in rtb.Document.Blocks.OfType<Paragraph>())
        {
            TextPointer pointer = null;
            foreach (Run r in p.Inlines.OfType<Run>())
            {
                int index = r.Text.IndexOf(".");
                if (index != -1)
                {
                    pointer = r.ContentStart.GetPositionAtOffset(index);
                }
            }
            if (pointer == null)
                continue;

            var firsSentence = new TextRange(p.ContentStart, pointer);
            ranges.Add(firsSentence);

        }
        foreach (var r in ranges)
        {
            r.ApplyPropertyValue(TextElement.FontWeightProperty, FontWeights.Bold);
        }
于 2017-02-11T23:34:04.113 回答