How to fill a Form.RTF with a Controls.RTF

Paolo Mossa 161 Reputation points
2023-12-04T07:36:12.7133333+00:00

I need to fill a document RTF (System.Windows.Forms.RichtextBox) from a Richtextbox (System.Windows.Control.RichTextbox). This because for printing. Actually I've done a class for printing RTF (Forms) with texts and images but I don't know how to print a RTF (Control).

I wish you to give me a way to print documents that contains text and images in RTF (Control) or give me a way to translate a document RTF (Control) into a RTF (Forms).

the code below shows the field resulTs that is a Controls.RichetextBox filled from a File. I remenber that RichtextBox is used in WPF program.

Thanks for an answer

           using (FileStream fileStream = File.Open(openFileDialog1.FileName, FileMode.Open))
                {
                    try
                    {
                        FlowDocument flowDocument = XamlReader.Load(fileStream) as FlowDocument;
                        resulTs.Document = flowDocument;

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,872 questions
Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,710 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,640 questions
0 comments No comments
{count} votes

Accepted answer
  1. Hui Liu-MSFT 47,336 Reputation points Microsoft Vendor
    2023-12-04T09:40:31.1+00:00

    Hi,@Paolo Mossa. Welcome to Microsoft Q&A Forum.

    If you want to translate the WPF content in RichTextBox to a format that can be used in a Windows Forms RichTextBox, you could leverage the System.Windows.Forms.RichTextBox for this purpose.

    app.csproj:

    
     <PropertyGroup>
     ...
       <UseWPF>true</UseWPF>
       <UseWindowsForms>true</UseWindowsForms>
     </PropertyGroup>
    
    
    

    MainWindow.xaml:

    <Window x:Class="RichTextBoxRTF.MainWindow"
          
            xmlns:local="clr-namespace:RichTextBoxRTF"
            xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <RichTextBox Name="rtb" HorizontalAlignment="Center" Height="200"  VerticalAlignment="Center" Width="300" BorderBrush="Gray" Padding="5,-2,-5,-2">
                <FlowDocument>
                    <BlockUIContainer>
                        <Image Source="E:\repos\1204\RichTextBoxRTF\1.PNG"  Width="300" Height="100"/>
                    </BlockUIContainer>
                    <Paragraph>hhhhhhhhhhh</Paragraph>
                    <Paragraph>hhhhhhhhhhhnnnnnn</Paragraph>
                </FlowDocument>
            </RichTextBox>
         
            <WindowsFormsHost Grid.Column="1">
                <wf:RichTextBox x:Name="wfrtb">
                    
                </wf:RichTextBox>
            </WindowsFormsHost>
        </Grid>
    </Window>
    

    MainWindow.xaml.cs:

    
    public partial class MainWindow : Window
    {
      public MainWindow()
      {
        InitializeComponent();
        string winFormsRtf = RtfTranslator.TranslateWpfRtfToWinFormsRtf(rtb);
        wfrtb.Rtf = winFormsRtf;
      }
    
      private void Button_Click(object sender, RoutedEventArgs e)
      {
    
      }
    }
    public static class RtfTranslator
    {
      public static string TranslateWpfRtfToWinFormsRtf(System.Windows.Controls.RichTextBox wpfRichTextBox)
      {
        TextRange textRange = new TextRange(wpfRichTextBox.Document.ContentStart, wpfRichTextBox.Document.ContentEnd);
    
        using (MemoryStream stream = new MemoryStream())
        {
          textRange.Save(stream, DataFormats.Rtf);
          stream.Seek(0, SeekOrigin.Begin);
    
          using (StreamReader reader = new StreamReader(stream))
          {
            return reader.ReadToEnd();
          }
        }
      }
    }
    
    

    The result:

    User's image

    Remember that Windows Forms and WPF formats may have some differences, especially when dealing with embedded objects or advanced formatting. Make sure to test and adjust accordingly based on your specific requirements.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Paolo Mossa 161 Reputation points
    2023-12-21T07:46:11.7833333+00:00

    Dear Mr. Hui Liu. I apologize for the delay in my reply:i got a flu. Unfortunatley I get a mistake warn when I load the document from a file. I don't no why but the error issue is about a image inner the file. So while I can save e reload the document correctly during the program is on but after I close the program the program don't load the old document saved. The error is :"Error in Bitmap at line 1 ..."

            private void Seleziona_Click(object sender, EventArgs e)
            {
                OpenFileDialog openFileDialog1 = new OpenFileDialog();
    
                openFileDialog1.InitialDirectory = "|DATADIRECTORY|";
                openFileDialog1.Filter = "All files (*.*)|*.*|pdf files (*.pdf)|*.pdf";
                openFileDialog1.FilterIndex = 4;
                openFileDialog1.RestoreDirectory = true;
                openFileDialog1.AddExtension = true;
    
    
                if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
         try
    {
                        using (FileStream fileStream =  File.Open(openFileDialog1.FileName, FileMode.OpenOrCreate))
                        {
                            FlowDocument flowDocument =      XamlReader.Load(fileStream) as FlowDocument;
                            resulTs.Document = flowDocument;
    
                        }
                    }
                    catch (Exception ex)
                    {
                        System.Windows.MessageBox.Show(ex.Message);
                    }
    
                }
            ```
    
    
    0 comments No comments