Xamarin.forms在Webview中显示PDF无法正常工作 [英] Xamarin.forms display PDF in webview not working

查看:200
本文介绍了Xamarin.forms在Webview中显示PDF无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从服务器下载了pdf流.在我的应用程序中,我将字节数组以pdf格式保存到本地文件夹中.但是,当我在网络视图中打开它时,它只会显示一个白页.

我遵循以下示例: https://developer.xamarin.com/recipes/cross-platform/xamarin-forms/controls/display-pdf .

这是我的xaml中的customwebview:

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

这是我的自定义视图代码:

 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); }
            }
    }

这是我检索pdf字节数组并将其存储在本地的方法:

 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);            
        }

我想念什么吗?

解决方案

如果我没记错的话,可以在iOS的网络视图中显示远程" PDF. 使用Android存在一些问题.我建议看一下此仓库 OpenPDF .我使用CustomRenderer和google工具显示PDF.我在某些Android版本上遇到了一些问题...但是您可以看一下.(这里亚当·佩德利 代码位于此处.

这是Android版的CustomRenderer

[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))));
            }
        }
    }
}

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?

解决方案

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))));
            }
        }
    }
}

这篇关于Xamarin.forms在Webview中显示PDF无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆