簡體   English   中英

啟動應用程序以從webview wp8查看pdf

[英]Launch app to view pdf from the webview wp8

當Webview上的頁面是pdf文件時,我正在嘗試啟動pdf應用程序查看器,但是我找不到如何做到這一點,這可能嗎?

如果您不熟悉Async,則應閱讀以下文章: 使用Async和Await的MSDN異步編程

我無法測試我的應用程序,因為我的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());
    }
}

不要忘記,您將不得不刪除某天創建的文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM