0

当 webview 上的页面是 pdf 文件时,我正在尝试启动 pdf 应用程序查看器,但我找不到如何做到这一点,这可能吗?

4

1 回答 1

1

如果您不熟悉 Async,您应该阅读以下文章: MSDN Asynchronous Programming with Async and Await

我无法测试我的应用程序,因为我的 WP8 手机当前不可用并且我无法在模拟器上安装 PDF 阅读器。

调用以下方法开始下载

WebClient pdfDownloader = null;
string LastFileName = ""; //To save the filename of the last created pdf

private void StartPDFDownload(string URL)
{
    pdfDownloader = new WebClient(); //prevents that the OpenReadCompleted-Event is called multiple times
    pdfDownloader.OpenReadCompleted += DownloadPDF; //Create an event handler
    pdfDownloader.OpenReadAsync(new Uri(URL)); //Start to read the website
}

async void DownloadPDF(object sender, OpenReadCompletedEventArgs e)
{
    byte[] buffer = new byte[e.Result.Length]; //Gets the byte length of the pdf file
    await e.Result.ReadAsync(buffer, 0, buffer.Length); //Waits until the rad is completed (Async doesn't block the GUI Thread)

    using (IsolatedStorageFile ISFile = IsolatedStorageFile.GetUserStoreForApplication())
    {
        try
        {
            LastFileName = "tempPDF" + DateTime.Now.Ticks + ".pdf";
            using (IsolatedStorageFileStream ISFileStream = ISFile.CreateFile(LastFileName))
            {
                await ISFileStream.WriteAsync(buffer, 0, buffer.Length);
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message + Environment.NewLine + ex.HResult,
                ex.Source, MessageBoxButton.OK);
            //Catch errors regarding the creation of file
        }
    }
    OpenPDFFile();
}

private async void OpenPDFFile()
{
    StorageFolder ISFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
    try
    {
        IStorageFile ISFile = await ISFolder.GetFileAsync(LastFileName);
        await Windows.System.Launcher.LaunchFileAsync(ISFile);
            //http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj206987%28v=vs.105%29.aspx
    }
    catch (Exception ex)
    {
        //Catch unknown errors while getting the file
        //or opening the app to display it
    }
}

要从 WebBrowser-Control 调用这些方法,您需要捕获导航事件。

YourWebBrowserControl.Navigating += YourWebBrowserControl_Navigating;

void YourWebBrowserControl_Navigating(object sender, NavigatingEventArgs e)
{
    if(e.Uri.AbsolutPath.EndsWith("pdf"))
    {
        StartPDFDownload(e.Uri.ToString());
    }
}

不要忘记您将不得不删除某天创建的文件。

于 2013-10-30T21:34:37.873 回答