I've got a WebView with some HTML content which I want to convert into RTF. I've looked at the RTF conversion functions out there and they all look a little flaky to be honest. So my idea is to copy content from the WebView into a RichEditBox, and save to RTF from there.

I've seen this example numerous times.

WebBrowser1.Document.ExecCommand("SelectAll", false, null);
WebBrowser1.Document.ExecCommand("Copy", false, null);

Unfortunately, WinRT's WebView control doesn't have a Document property, so I can't do this

Is there any way to pull the content from the control? To be clear, I don't want the HTML itself - I can get that already using

InvokeScript("eval", new string[] { "document.getElementById('editor').innerHTML;" });

What I want is the actual rendered HTML - the same as if I were to select everything in my WebView, press CTRL+C and then paste it into wordpad.

有帮助吗?

解决方案

This is part of a series of questions I asked in trying to accomplish a bigger task - converting HTML to RTF in a Windows Store App.

I'm delighted to report that the above can be done. I finally figured out how to do it, using DataPackage - normally used for sharing content between apps.

First, this javascript function must exist in the HTML loaded in the webview.

function select_body() {
    var range = document.body.createTextRange(); 
    range.select();
}

Next, you'll need to add using Windows.ApplicationModel.DataTransfer; to the top of your document. Not enough StackOverflow answers mention the namespaces used. I always have to go hunting for them.

Here's the code that does the magic:

// call the select_body function to select the body of our document
MyWebView.InvokeScript("select_body", null);

// capture a DataPackage object
DataPackage p = await MyWebView.CaptureSelectedContentToDataPackageAsync();

// extract the RTF content from the DataPackage
string RTF = await p.GetView().GetRtfAsync();

// SetText of the RichEditBox to our RTF string
MyRichEditBox.Document.SetText(Windows.UI.Text.TextSetOptions.FormatRtf, RTF);

I've spent about 2 weeks trying to get this to work. Its such a relief to finally discover I don't have to manually encode the file to RTF. Now if I can just get it to work the other way around, I'll be ecstatic. Not essential to the app I'm building, but it would be a lovely feature.

UPDATE

In retrospect you probably don't need to have the function in the HTML, you could probably get away with this (though I haven't tested):

MyWebView.InvokeScript("execScript", new string[] {"document.body.createTextRange().select();"})
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top