3
votes

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

enter image description here

And this is how it looks in the richtextbox in wpf

enter image description here

1
Adding a picture showing why and how "layout is off" could be much more helpful than posting code what simply loads rtf. Do you suspect there is a mistake in the code?Sinatr
I was thinking there might be a better way to read the document to have a more accurate display of it in the richtextboxPhil
just added pictures to illustrate the issuePhil
Try to save rft and compare with original one (you will have to use some hex-viewer), maybe this will give you a clue what is wrong. If both rtf are the same, then it's a matter of how RichTextBox displays rtf. I see there is a margin from left for a first paragraph, which seems to be ignored. Maybe it's because you not using SelectAll() before Load?Sinatr

1 Answers

0
votes

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: enter image description here