Download and Save PDF for viewing

10,635

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

Share:
10,635
InitLipton
Author by

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, 2022

Comments

  • InitLipton
    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
    poupou over 8 years
    Unless 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
    dharam over 4 years
    I tried the same no error nothing but, file isn't saving.
  • Jonty Morris
    Jonty Morris about 4 years
    Doesn't work on the majority of Android devices... The whole purpose of downloading the PDF locally is to skip this problem