linkedin
Working with PDFView and Pinch Zoom in Xamarin.Forms

Xamarin.Forms code runs on multiple platforms like Android, iOS, UWP, and each of them has its own file system. Using native APIs, we can do reading or writing files easily. Embedded resources are a simple solution for distributing data files with the application. In Xamarin.Forms there is no support or any feature for generating or viewing PDF files. We can achieve requirements such as view or generate PDF using native Support with the help of renderer for both Android and iOS platforms. 

 

However, you can also check how to generate PDF file from HTML string to empower your knowledge base on this topic.

 

Now talking about PDFView, it is a big problem in Android web view. To solve this problem, we can use google driver viewer and google doc viewer. We can also view PDF files using the pdfjs library through native support. We have to download the pdfjs file and put the folder in android and iOS platform projects. In the android platform put a folder inside Android Asset and in iOS put it inside the Resources folder. But the problem is that pdfjs does not support pinch zoom.

 

Let's create an application that is working with PDFView and pinch zoom. Create a new Project with Android and iOS platforms, choose mobile app project from mobile. Give appropriate names to the application and then select the blank app and platform - Android, iOS, UWP. If you are having a hard time doing this, then you can always hire a developer

 

Now create a new class file in the shared project for custom WebView. In this class inherit WebView for custom rendering and then add bindable properties. We are going to create two bindable properties uriProperty and isPDFProperty.

 

PdfViewRenderercs.cs file (For custom Webview)

 

using Xamarin.Forms;




namespace PdfView

{

    public class PdfViewRenderercs:WebView

    {

        public static readonly BindableProperty uriProperty = BindableProperty.Create(

          propertyName: "URI",

         returnType: typeof(string ),

         declaringType: typeof(PdfViewRenderercs),

         defaultValue: default(string)

);




        public string URI

        {

            get { return (string)GetValue(uriProperty); }

            set { SetValue(uriProperty, value); }

        }

        public static readonly BindableProperty isPDFProperty = BindableProperty.Create(

            propertyName: "IsPdf ",

            returnType: typeof(bool ),

            declaringType: typeof(PdfViewRenderercs ),

            defaultValue: default(bool)

            );

        public bool IsPdf

        {

            get { return (bool)GetValu(isPDFProperty);

 }

            set { SetValue ( isPDFProperty, value ) ; 

}

        }

    }

}

Now, we will implement a custom renderer in the Android platform. In Android, webview is not supported so we are going to use Google Driver Viewer to view the PDF. Note that the URL must be public and with extension .PDF

Use https://drive.google.com/viewerng/viewer?embedded=true&url=" + " url”; 

or 

https://docs.google.com/gview?embedded=true&url=" + " url" ;

 

Here, we have inherited the WebViewRenderer from renderer and created OnElementChange method and set url.

 

using Android.Content;

using PdfView;

using PdfView.Droid;

using Xamarin.Forms;

using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof( PdfViewRenderercs ), typeof( WebViewRendererAndroid ) ) ]

namespace PdfView.Droid

{

    public class WebViewRendererAndroid : WebViewRenderer

    {

        public WebViewRendererAndroid( Context context) : base( context)

        {

        }

        protected override void OnElementChanged( ElementChangedEventArgs<WebView> e )

        {

            base.OnElementChanged( e ) ;




            if (e.NewElement != null)

            {

                var pdfview = Element as PdfViewRenderercs ;

                Control.Settings.AllowUniversalAccessFromFileURLs = true ;

                If ( pdfview.IsPdf )

                {

                    var Url = "https://drive.google.com/viewerng/viewer?embedded=true&url=" + pdfview.URI;

                    Control.LoadUrl(Url) ;

                }

                else

                {

                    Control.LoadUrl( pdfview.URI) ;

                }

            }

        }

    }

}


MainPage Xamal file

 

<ContentPage xmlns= "http://xamarin.com/schemas/2014/forms"

             xmlns:x= "http://schemas.microsoft.com/winfx/2009/xaml"

             x:Class= "PdfView.MainPage">




    <StackLayout>

        <Button Text="Pdf" Clicked="pdf_button" />

    </StackLayout>




</ContentPage>





This is an implementation of the iOS platform, we have done the same things as we have implemented in the android platform:

 

using System;

using PdfView;

using PdfView.iOS;

using UIKit;

using Xamarin.Forms;

using Xamarin.Forms.Platform.iOS;




#pragma warning disable CS0612 // Type or member is obsolete

[assembly: ExportRenderer(typeof( PdfViewRenderercs ), typeof(PDFViewRendererios ))]

#pragma warning restore CS0612 // Type or member is obsolete

namespace PdfView.iOS

{

    [Obsolete]

    public class PDFViewRendererios: WebViewRenderer

    {

        protected override void OnElementChanged(VisualElementChangedEventArgs e )

        {

            base.OnElementChanged (e);




            if (NativeView != null && e.NewElement != null )

            {

                var pdfControl1 = NativeView as UIWebView ;




                if (pdfControl1 == null)

                    return;




                pdfControl1.ScalesPageToFit = true ;

            }

        }

}

}

MainPage code-behind file 

 

using Xamarin.Forms;

 

namespace PdfView

{

    public partial class MainPage : ContentPage

    {

        public MainPage()

        {

            InitializeComponent();

        }




        private async void pdf_button(object sender, EventArgs e)

        {

            await Navigation.PushModalAsync(new Page1() ) ;

        }

    }

}


 

Now, Implementing custom web view in XAML. First of all we have to add a namespace like this xmlns:Renderes="clr-namespace:PdfView" and then add custom web view. <Renderes:PdfViewRenderercs> </Renderes:PdfViewRenderercs>

 

Page1.Xaml

 

<ContentPage xmlns ="http://xamarin.com/schemas/2014/forms"

             xmlns:x ="http://schemas.microsoft.com/winfx/2009/xaml"

             xmlns:Renderes  ="clr-namespace:PdfView"

             x:Class ="PdfView.Page1">

    <ContentPage.Content>

        <Renderes:PdfViewRenderercs

            x:Name= " pdfviewpg1 "

            IsPdf=" True "

            VerticalOptions="FillAndExpand"

            HorizontalOptions="FillAndExpand">

        </Renderes:PdfViewRenderercs> 

</ContentPage.Content>

</ContentPage>

 

Page1.Xaml.cs file

 

using Xamarin.Forms;

using Xamarin.Forms.PlatformConfiguration;

using Xamarin.Forms.PlatformConfiguration.AndroidSpecific;

using Xamarin.Forms.Xaml;




namespace PdfView

{

    [XamlCompilation(XamlCompilationOptions.Compile )]

    public partial class Page1 : ContentPage

    {

        string url1 = "http://media.wuerth.com/stmedia/shop/catalogpages/LANG_it/1637048.pdf" ;

        public Page1 ()

        {

            InitializeComponent ();

            if (Device.RuntimePlatform = = Device.Android )

            {

                pdfviewpg1.URI = url1 ;

                pdfviewpg1.On<Android>().EnableZoomControls(true) ;

                pdfviewpg1.On<Android>().DisplayZoomControls(false) ;

            }

            else

            {

                pdfviewpg1.Source = url1 ;

            }

        }

}

}


To test pinch-zoom in the emulator use Control + Shift + Left Click and move the mouse. Here, we have created one Xamarin.Forms application working with PDFView and pinch zoom. We have created a custom WebView using renderer and create bindable properties in custom Webview. After that, we have implemented a custom renderer in the Android project, and in that file, we have inherited WebviewRenderer. At last, we have implemented a custom renderer in our XAML file, in XAML file we have added a namespace and a custom webview.

 

Conclusion 

 

In Xamarin.Forms there is no support for PDFView. We have to achieve this by using native support through custom renderers. We can view pdf files using the pdfjs library but the problem is that it does not support pinch-zoom functionality. PDFView is a big problem in android webview, to solve this problem we can use Google driver Viewer or Google doc viewer, and custom renderers. In this blog, we have created a simple app working with PDFView and pinch-zoom in which we have displayed one PDF file using google driver viewer with the help of a custom webview renderer. We have created a renderer file in the shared project and inherit webview and created bindable properties. And, in the Android project, we have created a class file for custom renderer and inherited webview renderer after that use a custom webview renderer in our XAML file by adding namespace and custom webview. We have also seen how to use pinch-zoom in the emulator.

 


 

In need of developers? Here’s where you can find the best pool of tech talents. With Cloud Employee, you can hire dedicated offshore developers across many technologies. Talk to us, learn more how Cloud Employee works, or see our Developer Pricing Guide.



Author Bio:

Vinod Satapara – Technical Director, iFour Technolab Netherlands.

Technocrat and entrepreneur with years of experience building large scale enterprise web, cloud and mobile applications using latest technologies like ASP.NET, CORE, .NET MVC, Angular and Blockchain. Keen interest in addressing business problems using the latest technologies and have been associated with Mobile Application development companies.

Hire A Developer Now!

Want to find out more? Fill out the form below and our team will contact you within 24 hours!
Unable to process your request. Unable to connect to the remote server. Please refresh and try again. You can also contact our hotline numbers > UK: +44 20 3289 6876 | AU: +61 285 996110 | US: +1 929 223 0231 | SE: +46 844 68 12 45 .

Join Our Newsletter!

Receive weekly newsletters on outsourcing, tech and exclusive promotions.

Are you a writer or blogger in the technology space looking to showcase your knowledge to an audience?

Lets talk

Featured Article



SidebarWidget-img-developer-guide

Download Our Developer Pricing Guide

We did an analysis on the difference between western and Philippines developer salaries. Uk, USA and Australia pricing comparisons available.

Download

Be up to date!

Sign up for our newsletters and get our latest outsourcing and tech news, and exclusive promotions.

How many hours do you want the developer to dedicate to working with you?

What skillsets are you looking to hire?

When do you need your developer to start ?