Getting RTF from WebView

Steps:

  1. Create a blank windows store 8.1 app.

  2. Add a WebView and RichEditBox in xaml of the page.
    1. <WebView Height="500" x:Name="webView" Loaded="webView_Loaded" NavigationCompleted="webView_NavigationCompleted" Width="500" HorizontalAlignment="Left" />  
    2. <RichEditBox x:Name="richEditBox" Width="500" Height="500" HorizontalAlignment="Right" />  
  3. I have tried this for html string as it’s is easy to add script in html.
    1. public static string GetHTML()  
    2. {  
    3.     return "<html>" +  
    4.         "<head>" +  
    5.         "<script type='text/javascript'>" +  
    6.         "function select_body() " +  
    7.         "{" +  
    8.         "var range = document.body.createTextRange(); " +  
    9.         "range.select();" +  
    10.         "}" +  
    11.         "</script>" +  
    12.         "<body>" +  
    13.         "<h1>My First Heading</h1>" +  
    14.         "<p>My first paragraph.</p>" +  
    15.         "</body></head></html>";  
    16. }  
  4. Now navigate webview to the html string.
    1. private void webView_Loaded(object sender, RoutedEventArgs e)  
    2. {  
    3.     webView.NavigateToString(GetHTML());  
    4. }  
  5. When the webPage is navigated we can notify a script and get rtf from webview.
    private async void webView_NavigationCompleted(WebView sender,
    1. WebViewNavigationCompletedEventArgs args)  
    2. {  
    3.     await webView.InvokeScriptAsync("select_body"null);  
    4.   
    5.     DataPackage p = await webView.CaptureSelectedContentToDataPackageAsync();  
    6.   
    7.     string rtf = await p.GetView().GetRtfAsync();  
    8.   
    9.     richEditBox.Document.SetText(Windows.UI.Text.TextSetOptions.FormatRtf, rtf);  
    10. }  
webview