Articles in this section
Category / Section

How to load PDF from file system?

4 mins read

This document illustrates loading a PDF document from the file system of a device into the PDF viewer control.

PCL/.NET Standard project

Add an interface with name IFileHelperService to the project using two method definitions to read the PDF from the file system. The first method is for iOS and Android, and the second one is for UWP that reads the PDF asynchronously.  

C#

namespace LoadFromFileDemo
{
    public interface IFileHelperService
    {
        //Gets the file stream in iOS and Android
        MemoryStream GetFileStream();
 
        //Gets the file stream in UWP
        Task<MemoryStream> GetFileStreamAsync();
 
    }
}

 

Add a ViewModel class with name ‘PdfViewerViewModel’ to the project and the class must implement the INotifyPropertyChanged interface. Define a property of type MemoryStream with name PdfStream. When this property is set, raise the PropertyChanged event with the property name as argument.

 

In the constructor, read the PDF into a MemoryStream using DependencyService and set it to the PdfStream property.

C#

namespace LoadFromFileDemo
{
    public class PdfViewerViewModel :  INotifyPropertyChanged
    {
        private MemoryStream pdfStream;
        public event PropertyChangedEventHandler PropertyChanged;
 
        public PdfViewerViewModel()
        {
            if (Device.OS == TargetPlatform.Windows || Device.OS == TargetPlatform.WinPhone)
 
                //Obtain the PDF stream from the UWP implementation of IFileHelperService. It is an asynchronous process
                //Since constructor cannot be async, this process must be done in another method
                SetFileStreamAsync();
 
            else
                pdfStream = DependencyService.Get<IFileHelperService>().GetFileStream();
        }
 
 
        private async void SetFileStreamAsync()
        {
            PdfStream = await DependencyService.Get<IFileHelperService>().GetFileStreamAsync();
        }
 
        //The PDF stream to be loaded into PdfViewer
        public MemoryStream PdfStream
        {
            get
            {
                return pdfStream;
            }
            set
            {
                pdfStream = value;
                PropertyChanged(this, new PropertyChangedEventArgs("PdfStream"));
            }
        }
 
    }
}

 

Set the BindingContext of the MainPage of the application to the PdfViewerViewModel class. Bind the InputFileStream property of PdfViewer to the PdfStream property.

XAML

<ContentPage.BindingContext>
        <local:PdfViewerViewModel/>
    </ContentPage.BindingContext>
    <Grid>
        <sfpdfviewer:SfPdfViewer x:Name="pdfViewerControl" InputFileStream="{Binding PdfStream}" />
    </Grid>

 

Android project

 

Implement the interface IFileHelperService in the Android project. It is sufficient to implement the body of the synchronous method ‘GetFileStream’.  The asynchronous method is only for UWP and is not used in Android.

 

Here, a PDF with name GIT_Succinctly.pdf stored in the Android device’s external storage is read into a MemoryStream.

C#

[assembly:Dependency(typeof(FileHelperService))]
 
namespace LoadFromFileDemo.Droid
{
    public class FileHelperService : IFileHelperService
    {
        public MemoryStream GetFileStream()
        {
            string path = Android.OS.Environment.ExternalStorageDirectory.Path;
            string filePath = Path.Combine(path, "GIT_Succinctly.pdf");
 
            return new MemoryStream(File.ReadAllBytes(filePath));
        }
 
        //Will not be called for Android
        public Task<MemoryStream> GetFileStreamAsync()
        {
            throw new NotImplementedException();
        }
    }
}

 

iOS project

 

Implement the interface IFileHelperService in the iOS project. It is sufficient to implement the body of the synchronous method ‘GetFileStream’.  The asynchronous method is only for UWP and is not used in iOS.

 

Here, a PDF with name iOS_Succinctly.pdf stored in the application’s personal folder is read into a MemoryStream.

C#

[assembly:Dependency(typeof(FileHelperService))]
 
namespace LoadFromFileDemo.iOS
{
    public class FileHelperService : IFileHelperService
    {
        public MemoryStream GetFileStream()
        {
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string filepath = Path.Combine(path, "iOS_Succinctly.pdf");
 
            return new MemoryStream(File.ReadAllBytes(filepath));
 
        }
 
        //Not called for iOS platform
        public Task<MemoryStream> GetFileStreamAsync()
        {
            throw new NotImplementedException();
        }
    }
}

 

UWP project

 

Implement the interface IFileHelperService in the UWP project. It is sufficient to implement the body of the asynchronous method ‘GetFileStreamAsync’.  The synchronous method ‘GetFileStream’ is only for Android and iOS and is used in UWP.

 

Here, a PDF with name iOS_Succinctly.pdf stored in the application’s personal folder is read into a MemoryStream.

C#

[assembly:Dependency(typeof(FileHelperService))]
 
namespace LoadFromFileDemo.UWP
{
    public class FileHelperService : IFileHelperService
    {
        //Will not be called for UWP
        public MemoryStream GetFileStream()
        {
            return null;
        }
 
        public async Task<MemoryStream> GetFileStreamAsync()
        {
            MemoryStream memoryStream = new MemoryStream();
            StorageFolder folder = ApplicationData.Current.LocalFolder;
            StorageFile file = await folder.GetFileAsync("WindowsStoreApps_Succinctly.pdf");
 
            using (Stream stream = await file.OpenStreamForReadAsync())
            {
                stream.Position = 0;
                stream.CopyTo(memoryStream);
            }
 
            return memoryStream;
        }
 
    }
}
 

 

Sample link:

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

 

Note:

The PDF files and the file paths used in the code snippet as well as in the sample are only meant to be examples. Before running the sample or using the code in your own application, please ensure that the PDF files exist in the specified paths. The file name and path can also be changed to suit your needs.

The input PDF files can be placed in the local disks of Windows (desktop/mobile) device and the storage directories of Android device manually.

But in iOS, manually placed or downloaded files cannot be accessed by an application. For an application, the file must be in the sandbox of the application according to the documentation to access a file.

If the PDF to be shown does not already exist in the application sandbox use the following procedure to save the PDF to a directory in the sandbox. The following code snippets are not included in the sample.

 

Add another method named ‘Save’ to the IFileHelperService interface.

C#

void Save(Stream inputStream);

 

This new method will also be defined in Android and UWP platforms. But, the body of the method does not need to be implemented in these platforms as they are never called. Now, implement the method in the FileHelperService class of iOS project.

C#

public void Save(Stream inputStream)
        {
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string filepath = Path.Combine(path, "iOS_Succinctly.pdf");
            FileStream fileStream = File.Open(filepath, FileMode.Create);
            inputStream.CopyTo(fileStream);
            fileStream.Flush();
            fileStream.Close();
        }

 

Call this save method from the constructor of the MainPage using DependencyService.

In below code snippet the variable ‘inputStream’ is a Stream object of a PDF either downloaded from URL or read from the assets.

C#

public MainPage
{
            InitializeComponent();
            Stream inputStream = typeof(App).GetTypeInfo().Assembly.GetManifestResourceStream("LoadFromFileDemo.Assets.iOS_Succinctly.pdf");
 
            DependencyService.Get<IFileHelperService>().Save(inputStream);
}

 

After saving the PDF to a directory, the previous code snippets can be removed from the project.

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