启动应用程序以从webview wp8查看pdf

时间:2013-10-30 19:37:17

标签: c# windows-phone-8

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

1 个答案:

答案 0 :(得分: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());
    }
}

不要忘记你必须删除有一天创建的文件。