Download, save( locally ) and display PDF from a link

pg90 picture pg90 · Sep 10, 2013 · Viewed 10.1k times · Source

I am developing Windows phone 8 application. In my application, i have to display PDF file in offline( without net connection ) mode, within application. For that i have to do the following,

  1. Download PDF file from a link( URL ) provided by server side.
  2. Save the downloaded PDF file in local storage.
  3. Open and display PDF file from local storage.

On searching, i found suggestions to use ComponentOne Studio's toolset called 'Studio for Windows Phone'. Unfortunately it is not free. Is there any way to implement in free of cost?

Any reference, samples or ideas will be greatly appreciated.

Answer

anderZubi picture anderZubi · Sep 10, 2013

You can download the PDF file and save it in Isolated Storage, to be able to view later offline using a PDF viewer app such Adobe Reader or PDF Reader.

So lets see how to do it step-by-step.

1- Download PDF file from a link( URL ) provided by server side:

WebClient client = new WebClient();
client.OpenReadCompleted += client_OpenReadCompleted;
client.OpenReadAsync(new Uri("http://url-to-your-pdf-file.pdf"));

2- Save the downloaded PDF file in local storage:

async void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    byte[] buffer = new byte[e.Result.Length];
    await e.Result.ReadAsync(buffer, 0, buffer.Length);

    using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (IsolatedStorageFileStream stream = storageFile.OpenFile("your-file.pdf", FileMode.Create))
        {
            await stream.WriteAsync(buffer, 0, buffer.Length);
        }
    }
}

3- Open and display PDF file from local storage:

// Access the file.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile pdffile = await local.GetFileAsync("your-file.pdf");

// Launch the pdf file.
Windows.System.Launcher.LaunchFileAsync(pdffile);