2

I download a pdf stream from my server. In my app I save the bytearray to a the local folder as pdf. But when I open it in the webview, it just shows a white page.

I followed this example: https://developer.xamarin.com/recipes/cross-platform/xamarin-forms/controls/display-pdf.

Here is customwebview in my xaml:

<local:CustomWebView x:Name="customView" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" />

Here is my code of the custom view:

 public class CustomWebView : WebView
    {        
        public static readonly BindableProperty UriProperty = BindableProperty.Create(propertyName: "Uri",
       returnType: typeof(string),
       declaringType: typeof(CustomWebView),
       defaultValue: default(string));

        public string Uri
            {
                get { return (string)GetValue(UriProperty); }
                set { SetValue(UriProperty, value); }
            }
    }

This is my method to retrieve the pdf byte array and store it locally:

 private async void ReadPDF()
        {
            var response = CommonLibrary.Helpers.HTTPClientHelper.DownloadPDF(AccountBL.AccessToken, APISettings.APIURI("api/booking/pdf"));
            var streamContent = response.Content as System.Net.Http.StreamContent;
            var bytes = CommonLibrary.Helpers.FileHelper.ReadBytes(await streamContent.ReadAsStreamAsync());
            var dir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            var fileName = "test.pdf";
            CommonLibrary.Helpers.FileHelper.WriteFileFromByteArray(bytes, dir, fileName);

           customView.Uri = System.IO.Path.Combine(dir, fileName);            
        }

Am I missing something?

Yaza
  • 195
  • 2
  • 10
  • 22
  • Have you tried getting your webview to go to a website, just to ensure whether it's a loading issue or a display issue? – Sasha Dec 15 '17 at 14:16
  • Hi Jaxi, you are right. A normal site is not loaded also. You have to just set the customWebview.Uri am I correct? – Yaza Dec 15 '17 at 15:26
  • Hi Jaxi, A normal site is loaded when I set the the source property -> customView.Source = "http://www.google.nl". When I set the source to the pdf location it's not working. – Yaza Dec 15 '17 at 15:35
  • Can you breakpoint and see if the dir variable is actually populated with a directory? – Sasha Dec 15 '17 at 15:48
  • I did and it's populated and I can find the file via the device monitor. – Yaza Dec 19 '17 at 14:23

2 Answers2

4

If I remember correctly, you can display a "remote" PDF in a webview on iOS. With Android there are some problems. I suggest to take a look to this repo OpenPDF. I use a CustomRenderer and a google tool to display the PDF. I have had some problems with some Android version... but you can take a look.(here a blog)

Otherwise there is @AdamPedley suggestion to use PDF JS Viewer Adam Pedley The code is here.

This is the CustomRenderer for Android

[assembly: ExportRenderer (typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace DisplayPDF.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:///android_asset/Content/{0}", WebUtility.UrlEncode (customWebView.Uri))));
            }
        }
    }
}
Alessandro Caliaro
  • 5,623
  • 7
  • 27
  • 52
  • Thanks for your answer, and openpdf is the way to go, but I'm experiencing some problems. Is it only working with a portable project? I have a shared project in my solution. – Yaza Dec 19 '17 at 14:26
  • I think it can work in a Shared Project without problem. It's only a WebView's Custom Renderer – Alessandro Caliaro Dec 19 '17 at 17:01
  • Hi Alessandro, I don't think I understand how this works. I have tried to create the renderer in the shared project without any succes. Where should I put this renderer? Is this only working for Android? I also want it to work for IOS? I don't understand the concept of the renderer. Could you please try and help me step by step? Thanks in advance. And happy xmas. – Yaza Dec 24 '17 at 18:34
  • @Yaza, there is a repo in the post. Yes, it is only for Android because iOS should works without problem using webview. You can take a look also to this solution https://blog.verslu.is/xamarin/xamarin-forms-xamarin/showing-pdf-files-xamarin-forms/ – Alessandro Caliaro Dec 24 '17 at 21:48
  • Hi Alessandro, thank you that worked perfectly. Thank you for your effort. I'm sorry for the delay. – Yaza Jan 01 '18 at 18:28
2

Following approach will allow you to view pdf in xamarin forms. If you are trying to open one from azure blob or you have valid URl.

WebView webView = new WebView();
var page = new ContentPage();
webView.Source = "https://docs.google.com/viewer?url=http://yourpdfurl.pdf";
page.Content = webView;
Navigation.PushModalAsync(page);