Logo Xoborg

Blog > PDF viewer from device storage in xamarin

Desarrollo

2 octubre 2017

PDF viewer from device storage in xamarin

In this post we are going to discover how to display PDFs on our Xamarin apps

PDF viewer from device storage in xamarin imagen

A couple of weeks ago, i was making a new PLC Xamarin app that reads info from an api, and also downloads files thorough it to the device storage. Some files are images and others PDFs that needed to be showed in the phone.

Searching a little bit, i found this link that helped me on this topic a lot:

Display a Local PDF File in a WebView - Xamarin This recipe shows how to display a local PDF file in a WebView control on each platform. developer.xamarin.com

That sounded as an official way to display those downloaded PDFs.

The IOS way to display them it’s very straight-forward, it’s just filling the web browser with our file, and it will handle the thing of being a PDF. Simple enough.

Android… it’s a little bit trickier. It needs a javascript code (https://mozilla.github.io/pdf.js/) that enables the browser to display the pdf. (When implemented it works fast enough)

But those examples are based on displaying an existing PDF inside our solution, and what we want to achieve it’s kind of different.

First of all, we need to download the file and then store it in our app. For this last point (Download process will change based on you needs) we’ll use PCLstorage:

dsplaisted/PCLStorage

Basically install this nuget in all projects in your solution and set the next code where you want to make this PDF download thing:

byte[] downloadedFile = await YourMethodToDonwloadFile(nameOfFile);

IFolder rootFolder = FileSystem.Current.LocalStorage;
IFolder folder = await rootFolder.CreateFolderAsync("MyFiles", CreationCollisionOption.OpenIfExists);

IFile file = await folder.CreateFileAsync(nameOfFile, CreationCollisionOption.ReplaceExisting);

using (Stream stream = await file.OpenAsync(FileAccess.ReadAndWrite))
{
  stream.Write(downloadedFile, 0, downloadedFile.Length)`
}

So we have our pdf saved on our device. Great. Now let’s load it to the web browser. (Follow the steps in Display a Local PDF File in a WebView)

Now we need to touch a couple of things in CustomWebViewRenderer files depending on the platform to achieve loading from storage.

IOS

Changes for IOS CustomWebViewRenderer:

using System.IO;
using System.Net;
using Foundation;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer (typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace ProjectTest.iOS
{
	public class CustomWebViewRenderer : ViewRenderer<CustomWebView, UIWebView>
	{
		protected override void OnElementChanged(ElementChangedEventArgs<CustomWebView> e)
		{
			base.OnElementChanged(e);

			if (Control == null)
			{
				SetNativeControl(new UIWebView());
			}
			if (e.OldElement != null)
			{
				// Cleanup
			}
			if (e.NewElement != null)
			{
        var ruta = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);

				var customWebView = Element as CustomWebView;
        string fileName = Path.Combine(ruta, string.Format("../Library/MyFiles/{0}", WebUtility.UrlEncode(customWebView.Uri)));
				Control.LoadRequest(new NSUrlRequest(new NSUrl(fileName, false)));
				Control.ScalesPageToFit = true;
			}
		}
	}
}

ANDROID

Changes for Android CustomWebViewRenderer:

using System;
using System.Net;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer (typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace ProjectTest.Droid
{
	public class CustomWebViewRenderer : WebViewRenderer
	{
		protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
		{
			base.OnElementChanged(e);

			if (e.NewElement != null)
			{
				var customWebView = Element as CustomWebView;
				Control.Settings.AllowUniversalAccessFromFileURLs = true;
				Control.LoadUrl(string.Format("file:///android_asset/pdfjs/web/viewer.html?file={0}", string.Format("file:///data/user/0/com.your.company.name/files/MyFiles/{0}", WebUtility.UrlEncode(customWebView.Uri))));
			}
		}
	}
}

Ending the stuff After doing those changes you can easily load the desired pdf as follows:

var WebView = new CustomWebView { Uri = nameOfFile })

And it will load from your device storage! Awesome!

Thanks for your time! And if you liked this article subscribe below! Enjoy Xamarin!!

Made with in Spain

Logo Xoborg Oscuro

© 2013 - 2024 Xoborg Technologies S.L. Todos los derechos reservados. Paseo Canalejas, 57-61 entre planta, oficina Num5, Salamanca 37001, Castilla y León, España.

Distintivo ENS Certificación Media