I'm using a post call to get a byte stream with all the data for a PDF, then I want to open the PDF using the default program in Android. Will later do for iOS.
Here's my code:
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;
}
What I have now downloads the pdf as a byte stream then makes a window pop up then close. What should I do to fix? I'd rather not pay for any packages and ideally I'd like to have it prompt for what program to open with.
The file system is different between Ios and Android . So, you need use DependencyService to save and load the PDF file on different platform.
Thanks @B.6242, in this issue , @B.6242 has implemented it in both Android and Ios with DependencyService
, you can refer to it.
Here is an issue about how to use the file system on different platforms.
Got it to work by following this: https://developer.xamarin.com/recipes/cross-platform/xamarin-forms/controls/display-pdf/
In the code above, change OnItemSelected to this, where PDFViewPage uses the customWebView described in the above link:
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));
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.