Download and Save PDF for viewing
Solution 1
Do not use DownloadStringAsync
for "binary" data, use DownloadDataAsync
:
Downloads the resource as a Byte array from the URI specified as an asynchronous operation.
private void PdfClickHandler ()
{
var webClient = new WebClient ();
webClient.DownloadDataCompleted += (s, e) => {
var data = e.Result;
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = $"{_blueways}.pdf";
File.WriteAllBytes (Path.Combine (documentsPath, localFilename), data);
InvokeOnMainThread (() => {
new UIAlertView ("Done", "File downloaded and saved", null, "OK", null).Show ();
});
};
var url = new Uri ("_blueway.PDF");
webClient.DownloadDataAsync (url);
}
Solution 2
// Retrieving the URL
var pdfUrl = new Uri("url.pdf"); //enter your PDF path here
// Open PDF URL with device browser to download
Device.OpenUri(pdfUrl);
![InitLipton](https://i.stack.imgur.com/qTSBu.jpg?s=256&g=1)
InitLipton
Any fool can write code that a computer can understand. Good programmers write code that humans can understand - Martin Fowler SOreadytohelp
Updated on June 15, 2022Comments
-
InitLipton about 2 years
Im trying to download a PDF document from my app and display it in IBooks or at least make it available to read some how when its completed downloading.
I followed the download example from Xamarin which allows me download the PDF and save it locally. Its being save in the wrong encoding also.
This is what I've tried so far.
private void PdfClickHandler() { var webClient = new WebClient(); webClient.DownloadStringCompleted += (s, e) => { var text = e.Result; // get the downloaded text string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string localFilename = $"{_blueways}.pdf"; // writes to local storage File.WriteAllText(Path.Combine(documentsPath, localFilename), text); InvokeOnMainThread(() => { new UIAlertView("Done", "File downloaded and saved", null, "OK", null).Show(); }); }; var url = new Uri(_blueway.PDF); webClient.Encoding = Encoding.UTF8; webClient.DownloadStringAsync(url); }
-
poupou over 8 yearsUnless you know the size of the file you're downloading (and that it is small) you better download it into a file (or risk running out of memory).
-
dharam over 4 yearsI tried the same no error nothing but, file isn't saving.
-
Jonty Morris about 4 yearsDoesn't work on the majority of Android devices... The whole purpose of downloading the PDF locally is to skip this problem