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

时间:2018-02-22 22:09:22

标签: c# android json xamarin io

我使用post调用来获取包含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作为字节流下载,然后弹出一个窗口然后关闭。我该怎么办?我宁愿不为任何套餐买单,理想情况下我想提示要开放哪个套餐。

2 个答案:

答案 0 :(得分:1)

Ios and Android之间的文件系统不同。因此,您需要使用DependencyService在不同平台上保存和加载PDF文件。

感谢@ B.6242,在此issue中,@ B.6242已在Android和Ios中使用DependencyService实现了它,您可以参考它。

Here is an issue 关于如何在不同平台上使用文件系统。

答案 1 :(得分:0)

按照以下方式开展工作:https://developer.xamarin.com/recipes/cross-platform/xamarin-forms/controls/display-pdf/

在上面的代码中,将OnItemSelected更改为this,其中PDFViewPage使用上述链接中描述的customWebView:

        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));
        }
    }