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

问题描述 投票:1回答:2

我正在使用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作为字节流下载然后弹出一个窗口然后关闭。我该怎么办?我宁愿不为任何包付费,理想情况下我想让它提示打开什么程序。

c# android json xamarin io
2个回答
1
投票

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

谢谢@ B.6242,在这个issue中,@ B.6242已经用DependencyService在Android和Ios中实现了它,你可以参考它。

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


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));
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.