Loading, please wait...

A to Z Full Forms and Acronyms

Working with PDFView and Pinch Zoom in Xamarin.Forms

In this article, you will learn how to implement PDF view with pinch-zoom in xamarin forms.

Introduction

Xamarin.Forms code runs on multiple platforms, each of which has its own filesystem. This means that reading and writing files are most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

PDF Viewer

The Problem(Android)

PDFView doesn't support the default webview in android xamarin forms.

Solution

The PDFView is biggest issue in android webview. I solved this problem by using google drive viewer and google doc viewer.
there is another way to view pdf file using pdfjs. but pdfjs doesn't support pinch zoom.


https://github.com/mozilla/pdf.js/issues/2582


Note: The pdf URL must be the extension.PDF and public.

Prerequisites

  • Visual Studio 2017 or later (Windows or Mac)

Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You will learn more by going through the steps yourself.

Create a new or existing Xamarin forms (.Net standard) Project with Android and iOS Platform.

Choose the Mobile App (Xamarin. forms) project under C# and Mobile.

Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".

Now, select the blank app and target platforms - Android, iOS, and Windows (UWP).

Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select the XAML page and double-click to open the MainPage.Xaml page.

You now have a basic Xamarin.Forms app. Click the Play button to try it out.

Create a Custom Webview

Here going to create a custom webview inherit from webview for custom rendering. I'm going to create two bindable properties following.

1.Uri
2.IsPDF

PDFView.cs

public class PDFView: WebView
    {
        public static readonly BindableProperty UriProperty = BindableProperty.Create(propertyName: "Uri",
                returnType: typeof(string),
                declaringType: typeof(PDFView),
                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(PDFView),
                defaultValue: default(bool));

        public bool IsPDF
        {
            get { return (bool)GetValue(IsPDFProperty); }
            set { SetValue(IsPDFProperty, value); }
        }

    }

Android Implementation

Here, Create a custom renderer for webview. for android the webview doesn't support pdf file preview. so I'm going view pdf files Google drive viewer.

Note: The Url must be extension .PDF and public.

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

Another Solution


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

PDFViewRenderer.cs

[assembly: ExportRenderer(typeof(PDFView), typeof(PDFViewRenderer))]
namespace PDFPOC.Droid
{
    public class PDFViewRenderer : WebViewRenderer
    {
        public PDFViewRenderer(Context context) : base(context)
        {
        }
        protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null)
            {


                var pdfView = Element as PDFView;
                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);
                }

            }
        }
    }
}

iOS Implementation

Here, Create a custom renderer for webview to load pdf files in webview.

PDFViewRenderer.cs

[assembly: ExportRenderer(typeof(PDFView), typeof(PDFViewRenderer))]

namespace PDFPOC.iOS
{
    public class PDFViewRenderer : WebViewRenderer
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            if (NativeView != null && e.NewElement != null)
            {
                var pdfControl = NativeView as UIWebView;

                if (pdfControl == null)
                    return;

                pdfControl.ScalesPageToFit = true;
            }
        }
    }
}

Consuming the CustomWebview

Here, consume the Custom Webview in your xaml

Add Namespace

xmlns:controls="clr-namespace:PDFPOC.Controls"

Add your Custom Webview

PDFView.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
              xmlns:controls="clr-namespace:PDFPOC.Controls"
             mc:Ignorable="d"
             x:Class="PDFPOC.PDFViewer">
    <ContentPage.Content>
        <StackLayout BackgroundColor="Green" 
                     HorizontalOptions="CenterAndExpand" 
                     VerticalOptions="CenterAndExpand">
            <controls:PDFView x:Name="pdfView"  
                              IsPDF="True" 
                              HeightRequest="1000"
                              WidthRequest="1000"
                              VerticalOptions="FillAndExpand"  />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

PDFView.xaml.cs

public partial class PDFViewer : ContentPage
    {
        string url = "http://media.wuerth.com/stmedia/shop/catalogpages/LANG_it/1637048.pdf";
        public PDFViewer()
        {
            InitializeComponent();

            if (Device.RuntimePlatform == Device.Android)
            {
                pdfView.Uri = url;
                pdfView.On<Android>().EnableZoomControls(true);
                pdfView.On<Android>().DisplayZoomControls(false);
            }

            else
                pdfView.Source = url;
        }

    }

Click the "Play" button to try it out

Android

You can test Pinch zoom by emulator also use Shift + ctrl + Left click and mouse move

iOS

 

 

The simulator also supports pinch-zoom use Alt + Left click and mouse move

Wow, It's working.

Full source code available below GitHub repository

https://github.com/susairajs/XamarinForms-PDFView-PinchZoom


I hope you have understood how to implement a PDF view with pinch-zoom in Xamarin.Forms.

Thanks for reading. Please share your comments and feedback. Happy Coding :)

A to Z Full Forms and Acronyms