Articles in this section
Category / Section

How to load PDF document in SfPdfViewer Xamarin.Forms from given URL?

2 mins read

PDF documents can be loaded into the Pdf Viewer from a given URL by downloading the PDF and then loading the stream of the downloaded file to the PdfViewer. Refer to the following code snippets.

 

Add a new ViewModel class named PdfViewerViewModel to the PCL or .NET Standard project. The class must implement the INotifyPropertyChanged interface.

C#

public class PdfViewerViewModel : INotifyPropertyChanged

 

Define a new property named PdfDocumentStream in the class. In the setter accessor of the property raise the PropertyChanged event once the value is set to the private field of the property.

C#

public Stream PdfDocumentStream
{
   get { return pdfDocumentStream; }
   set
   {
       //Check the value whether it is the same as the currently loaded stream
       if (value != pdfDocumentStream)
       {
          pdfDocumentStream = value;
          PropertyChanged(this, new PropertyChangedEventArgs("PdfDocumentStream"));
       }
   }
}

 

Define an asynchronous method that gets the stream from the given URL.

C#

private async Task<Stream> DownloadPdfStream(string URL)
{
     HttpClient httpClient = new HttpClient();
     HttpResponseMessage response = await httpClient.GetAsync(URL);
   //Check whether redirection is needed
     if((int)response.StatusCode == 302)
     {
      //The URL to redirect is in the header location of the response message
          HttpResponseMessage redirectedResponse = await httpClient.GetAsync(response.Headers.Location.AbsoluteUri);
          return await redirectedResponse.Content.ReadAsStreamAsync();
     }
     return await response.Content.ReadAsStreamAsync();}

 

The stream returned by the previous method must be set to the PdfDocumentStream property in the constructor. As the constructor cannot be executed asynchronously, define another asynchronous method and call the DownloadPdfStream method from inside it.

C#

private async void SetStreamAsync()
{
   PdfDocumentStream = await DownloadPdfStream(URL);
}

Call this method from the constructor synchronously.

C#

public PdfViewerViewModel()
{
   SetStreamAsync();
}

 

Bind the InputFileStream property of PdfViewer to the PdfDocumentStream property.

XAML

<viewer:SfPdfViewer x:Name="pdfViewerControl" InputFileStream="{Binding PdfDocumentStream}" />

 

 


Sample link:

https://www.syncfusion.com/downloads/support/directtrac/general/ze/LoadPDFFromURL783209975.zip

Note

PdfViewer loads the PDF as soon as the InputFileStream property is set to a stream. In the previous sample PDFs may not load immediately. This is due to the time taken for the stream to be fetched from the URL asynchronously. This must not be taken as a PdfViewer defect.

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments
Please sign in to leave a comment
Access denied
Access denied