将PDF作为字节流下载,然后在Xamarin.forms中的默认Android应用程序中打开



我正在使用帖子调用来获取带有PDF所有数据的字节流,然后我想使用Android中的默认程序打开PDF。以后会为iOS做。

这是我的代码:

        async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        Publication p = (Publication)e.SelectedItem;
        Debug.WriteLine(p);
        if (p.folderID.Equals("-1"))
        {
            using (Stream respStream = await post(p.docNum))
            {
                byte[] buffer = new byte[respStream.Length];
                respStream.Read(buffer, 0, buffer.Length);
                string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                File.WriteAllBytes(path + "foo.pdf", buffer);
                Device.OpenUri(new Uri(path + "foo.pdf"));
            }
        }
        else
        {
            await Navigation.PushAsync(new PublicationsPage(p.folderID));
        }
    }
    private async Task<Stream> post(string id)
    {
        Dictionary<string, string> dir = new Dictionary<string, string>();
        dir.Add("LoginID", App.user.login_id);
        dir.Add("docID", id);
        var jsonReq = JsonConvert.SerializeObject(dir);
        Debug.WriteLine("req: " + (String)jsonReq);
        var content = new StringContent(jsonReq, Encoding.UTF8, "application/json");
        var response = await client.PostAsync(url, content);
        var responseStream = await response.Content.ReadAsStreamAsync();
        return responseStream;
    }

我现在已经下载了PDF作为字节流,然后将窗口弹出然后关闭。我该怎么办?我宁愿不支付任何包裹,理想情况下,我想提示使用哪个程序打开。

iOS和android之间的文件系统不同。因此,您需要使用dependencyService来保存和加载PDF文件在不同的平台上。

感谢 @b.6242,在本期中, @b.6242已在Android和iOS中使用DependencyService实现了它,您可以参考它。

这是关于如何在不同平台上使用文件系统的问题。

通过以下内容让它起作用:https://developer.xamarin.com/recipes/cross-platform/xamarin-forms/controls/controls/display-pdf/

在上面的代码中,将onitemsemectect与此更改为PDFViewPage使用上面链接中描述的自定义WebView:

        async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        Publication p = (Publication)e.SelectedItem;
        Debug.WriteLine(p);
        if (p.folderID.Equals("-1"))
        {
            using (Stream respStream = await post(p.docNum))
            {
                byte[] buffer = new byte[respStream.Length];
                respStream.Read(buffer, 0, buffer.Length);
                string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                File.WriteAllBytes(path + "foo.pdf", buffer);
                await Navigation.PushAsync(new PDFViewPage(path + "foo.pdf"));
                //Device.OpenUri(new Uri(path + "foo.pdf"));
            }
        }
        else
        {
            await Navigation.PushAsync(new PublicationsPage(p.folderID));
        }
    }

最新更新