Articles in this section
Category / Section

How to load PDF from the file system

2 mins read

This section explains loading a PDF document from the file system of an Android device into the PDF viewer control.

Add a new method named “ReadPdfStreamFromExternalStorage” to the MainActivity Class of the android application project.

The entire ReadPdfStreamFromExternalStorage method is given as follows.

C# 

private Stream ReadPdfStreamFromExternalStorage() 
{ 
//Get the path of external storage directory. Here, we used download directory to read the PDF document 
String path = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath; 
//Read the specific PDF document from the download directory 
Java.IO.File filePath = new Java.IO.File(path+"/test.pdf"); 
// Check whether the file is exist in the download directory 
if (filePath.Exists()) 
{ 
// Convert the file path to stream to display it into SfPdfViewer 
return new FileStream(filePath.AbsolutePath, FileMode.Open, FileAccess.Read); 
} 
else 
{ 
// throw exception if the file is not found in the appropriate directory 
throw new FileNotFoundException("File not found"+ filePath.AbsolutePath.ToString()); 
} 
} 
 

 

Call this ReadPdfStreamFromExternalStorage method in the OnCreate overridden method of the MainActivity class to obtain the file stream of the PDF document to load into the PDF viewer control. Please refer the following code snippet for reference.

C#

protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
//Set the activity content from a layout resource
SetContentView(Resource.Layout.Main);
// Finds a SfPdfViewer that was identified by resource id
var pdfViewerControl = FindViewById<SfPdfViewer>(Resource.Id.pdfviewerControl);
//Read the PDF document as stream as from External Storage
Stream pdfStream =  ReadPdfStreamFromExternalStorage();
//Load the Pdf document stream into SfPdfViewer
pdfViewerControl.LoadDocument(pdfStream);
}

 

Sample link:

https://www.syncfusion.com/downloads/support/directtrac/general/ze/PdfViewerSample-1562340568.zip

Note:

Kindly ensure the PDF document that you want to display in the SfPdfViewer is available in the appropriate external storage directory. 

 

See Also:

To learn more about loading a PDF document from the file system in the PdfViewer Xamarin.Forms, kindly refer to the following link.

https://www.syncfusion.com/kb/8858/how-to-load-pdf-from-file-system

 

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