Articles in this section
Category / Section

How to load PDF using Prism 7.0 dependency injection?

4 mins read

Install Prism.Unity.Forms package to your projects in the Visual Studio solution.

 

PCL/ .NET Standard

 

Open the App.xaml file and change the <Application> to <PrismApplication>.

 

XAML

<prism:PrismApplication xmlns="http://xamarin.com/schemas/2014/forms"
 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
 x:Class="PdfViewerDependencyInjection.App"
 xmlns:prism="clr-namespace:Prism.Unity;assembly=Prism.Unity.Forms">

 

Open App.xaml.cs file and change Application to PrimsApplication.

C#

public partial class App : PrismApplication

 

Modify the constructor of the App class as follows..

C#

public App (IPlatformInitializer initializer = null) : base(initializer)
{ 
}

 

In the same App class, set the BindingContext of the MainPage to the PdfViewerViewModel class using the RegisterTypes method.

C#

//Sets the BindingContext of the MainPage to PdfViewerViewModel
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
   containerRegistry.RegisterForNavigation<MainPage, PdfViewerViewModel>();
}

 

Place the call to InitializeComponents method in OnInitilaized method. Also, set the MainPage property of the App.

C#

protected override void OnInitialized()
{
    InitializeComponent();
    NavigationService.NavigateAsync("MainPage");
}

 

Include an interface to the portable project with name IFileHelperService. This interface defines the methods that fetch streams from the PDF files to be loaded.

C#

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 to the project with name PdfViewerViewModel that implements the INotifyPropertyChanged interface. Define a property PdfStream of type MemoryStream in the class. The stream to be loaded into PdfViewer is read from the file location using IFileHelperService interface and set to the PdfStream property.

C#

public class PdfViewerViewModel :  INotifyPropertyChanged
{
    private MemoryStream pdfStream;
    public event PropertyChangedEventHandler PropertyChanged;
 
    public PdfViewerViewModel(IFileHelperService fileHelperService)
    {
        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(fileHelperService);
 
        else
            pdfStream = fileHelperService.GetFileStream();
    } 
 
        
    private async void SetFileStreamAsync(IFileHelperService fileHelperService)
    {
        PdfStream = await fileHelperService.GetFileStreamAsync();
    }
 
   //The PDF stream to be loaded into PdfViewer
    public MemoryStream PdfStream
    {
       get
       {
           return pdfStream;
       }
       set
       {
           pdfStream = value;
           PropertyChanged(this, new PropertyChangedEventArgs("PdfStream"));
       }
    }
 
}

 

Bind the InputFileStream property of the PdfViewer in XAML to the PdfStream property defined in the ViewModel class.

XAML

<Grid>
   <sfpdfviewer:SfPdfViewer x:Name="pdfViewerControl" InputFileStream="{Binding PdfStream}" />
</Grid>

 

Android

Implement the IFileHelperService interface in Android.

C#

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

 

Define a static field of type FileHelperService in the MainActivity class.

C#

public static FileHelperService fileHelperService = new FileHelperService();

 

Include a new class to the Android project with name AndroidInitializer that implements the IPlatformInitializer interface. Register the static field defined in MainActivity class with the containerRegistry.

 

 

C#

public class AndroidInitializer : IPlatformInitializer
{
    public void RegisterTypes(IContainerRegistry containerRegistry)
    {
       containerRegistry.RegisterInstance<IFileHelperService>(
       MainActivity.fileHelperService);
    }
}

 

Pass an instance of the AndroidInitializer class as a parameter to the constructor of App class in the LoadApplication method call in MainActivity.

C#

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
 
    global::Xamarin.Forms.Forms.Init(this, bundle);
    LoadApplication(new App(new AndroidInitializer()));
}

 

iOS

Implement the IFileHelperService interface in iOS platform.

C#

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

 

Define a static field of type FileHelperService in the AppDelegate file.

C#

public static FileHelperService fileHelperService = new FileHelperService();

 

Include a new class to the iOS project with name IOSInitializer, which implements the IPlatformInitializer interface. Register the static field defined in the AppDelegate file with contentRegistry.

C#

public class IOSInitializer : IPlatformInitializer
{
    public void RegisterTypes(IContainerRegistry containerRegistry)
    {
         containerRegistry.RegisterInstance<IFileHelperService>(
         AppDelegate.fileHelperService);
    }
}

 

Pass an instance of the IOSInitializer class as a parameter to the constructor of App class in the call to LoadApplication in AppDelegate.

C#

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    global::Xamarin.Forms.Forms.Init();
    LoadApplication(new App(new IOSInitializer()));
    new SfPdfDocumentViewRenderer();
    return base.FinishedLaunching(app, options);
}

 

UWP

Implement the IFileHelperService interface in UWP platform.

C#

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

 

Define a static field of type FileHelperService in the MainPage class of the UWP project.

C#

public static FileHelperService fileHelperService = new FileHelperService();

 

Add a class with name WindowsInitializer to the UWP project, which implements the IPlatformInitializer interface. Register the instance of the FileHelperService that has been created in the MainPage with contentRegistry.

C#

public class WindowsInitializer : IPlatformInitializer
{
    public void RegisterTypes(IContainerRegistry containerRegistry)
    {
   containerRegistry.RegisterInstance<IFileHelperService>(MainPage.fileHelperService);
    }
 
}

 

Pass an instance of the class WindowsInitializer as an argument to the constructor of the App class in the LoadApplication method call in MainPage.

 

C#

public MainPage()
{
    this.InitializeComponent();
    LoadApplication(new PdfViewerDependencyInjection.App(new WindowsInitializer()));
}

 

Sample link:

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

 

 

Note:

Before running the sample, place the PDF document in the folder locations used in the FileHelperService class of the three platforms. Also, change the PDF file name to the name of the PDF you are using.

 

 

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