简体   繁体   中英

rtf layout changed after loading into richtextbox wpf c#

I have an rtf of which the layout displays perfect when I open it in word, but when I try to open it in the richtextbox in my wpf app, the layout is off, and I would love to keep it the same. Is there a way of doing this? A different way of reading the file?

Here is the code I use to load the rtf file

openFile.InitialDirectory = @"C:\";
openFile.Filter = "Text files (*.rtf)|*.rtf|All Files (*.*)|*.*";
openFile.RestoreDirectory = true;
openFile.Title = "Select Script";

if (openFile.ShowDialog() == true)
{
    string originalfilename = System.IO.Path.GetFullPath(openFile.FileName);

    TextRange range;
    FileStream fStream;

    if (openFile.CheckFileExists)
    {
         range = new TextRange(rtfMain.Document.ContentStart, rtfMain.Document.ContentEnd);
         fStream = new FileStream(originalfilename, System.IO.FileMode.OpenOrCreate);
         range.Load(fStream, DataFormats.Rtf);
         fStream.Close();
    }
}

and this is the xaml

 <RichTextBox IsReadOnly="True" x:Name="rtfMain" HorizontalAlignment="Left" Width="673" VerticalScrollBarVisibility="Visible"/>

here is how the orginal looks like

在此处输入图片说明

And this is how it looks in the richtextbox in wpf

在此处输入图片说明

Try something like this:

 if (openFile.CheckFileExists)
    {
      range = new TextRange(rtfMain.Document.ContentStart, rtfMain.Document.ContentEnd);
      using (var fStream = new StreamReader(originalfilename, Encoding.Default,true))
      {
        range.Text = fStream.ReadToEnd();
      }
    }

and in xaml:

<RichTextBox IsReadOnly="True" x:Name="rtfMain" HorizontalAlignment="Left" 
                     Width="673" VerticalScrollBarVisibility="Visible" Height="250">
            <RichTextBox.Resources>
                <Style TargetType="{x:Type Paragraph}">
                    <Setter Property="Margin" Value="0"/>
                </Style>
            </RichTextBox.Resources>
        </RichTextBox>

how it looks:在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM