Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download and Save PDF for viewing

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);
}
like image 318
InitLipton Avatar asked Sep 26 '22 12:09

InitLipton


1 Answers

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);
}
like image 179
SushiHangover Avatar answered Oct 11 '22 13:10

SushiHangover