【问题标题】:Show a pdf into a webview from a link inside that Website Xamarin android从该网站 Xamarin android 中的链接将 pdf 显示为 webview
【发布时间】:2018-07-23 13:08:42
【问题描述】:

在我的应用程序中,我实现了一个 webview 来显示指向该 webview 的网站链接。现在该网站有一个包含 pdf 文件链接的按钮。如果我点击网站上的那个按钮,它会在网上显示一个 pdf 文件。但是,如果我尝试在我的应用程序中将其打开到 webview 中,则什么也不会发生。我是 Xamarin android 的新手。我找不到任何合适的方法。这是我将网站显示到 webview 中的代码。

单击网站上的链接时,我想重新加载 pdf。但是结果和以前一样

修改后的代码

    namespace Xamarin.PDFView
{
    [Activity (Label = "PDFView", MainLauncher = true, Icon = "@drawable/icon")]

    public class MainActivity : Activity
    {
        private  string _documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
        private  string _pdfPath;
        private  string _pdfFileName = "thePDFDocument.pdf";
        private  string _pdfFilePath;
        private WebView _webView;
        private string _webUrl = "https://Link of thewebsite";
        private string _pdfURL = "https://Link of thewebsite/25052016.pdf";
        private WebClient _webClient = new WebClient();

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);
            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            _webView = FindViewById<WebView> (Resource.Id.webView1);
            var settings = _webView.Settings;
            settings.JavaScriptEnabled = true;
            settings.AllowFileAccessFromFileURLs = true;
            settings.AllowUniversalAccessFromFileURLs = true;
            settings.BuiltInZoomControls = true;
            _webView.SetWebViewClient(new WebViewClient());
            _webView.SetWebChromeClient(new WebChromeClient());
            _webView.LoadUrl(_webUrl);

        }
        public override bool OnTouchEvent(MotionEvent e)
        {
            if (_webUrl.Contains(".pdf"))
            {
               DownloadPDFDocument();
            }

            return base.OnTouchEvent(e);
        }

        protected override void OnResume ()
        {
            base.OnResume ();
            _webView.LoadUrl( "javascript:window.location.reload( true )" );

        }

        protected override void OnPause ()
        {
            base.OnPause ();
            _webView.ClearCache(true);
        }

        private void DownloadPDFDocument()
        {
            AndHUD.Shared.Show(this, "Downloading PDF\nPlease Wait ..", -1, MaskType.Clear);

            _pdfPath = _documentsPath + "/PDFView";
            _pdfFilePath  = Path.Combine(_pdfPath, _pdfFileName);

            // Check if the PDFDirectory Exists
            if(!Directory.Exists(_pdfPath)){
                Directory.CreateDirectory(_pdfPath);
            }
            else{
                // Check if the pdf is there, If Yes Delete It. Because we will download the fresh one just in a moment
                if (File.Exists(_pdfFilePath)){
                    File.Delete(_pdfFilePath);
                }
            }

            // This will be executed when the pdf download is completed
            _webClient.DownloadDataCompleted += OnPDFDownloadCompleted;
            // Lets downlaod the PDF Document
            var url = new Uri(_pdfURL);
            _webClient.DownloadDataAsync(url);
        }

        private void OnPDFDownloadCompleted (object sender, DownloadDataCompletedEventArgs e)
        {
            // Okay the download's done, Lets now save the data and reload the webview.
            var pdfBytes = e.Result;
            File.WriteAllBytes (_pdfFilePath, pdfBytes);

            if(File.Exists(_pdfFilePath))
            {
                var bytes = File.ReadAllBytes(_pdfFilePath);
            }

            _webView.LoadUrl("file:///android_asset/pdfviewer/index.html?file=" + _pdfFilePath);

            AndHUD.Shared.Dismiss();
        }


        public class HelloWebViewClient : WebViewClient
        {
            public override bool ShouldOverrideUrlLoading(WebView view, IWebResourceRequest request)
            {
                view.LoadUrl(request.Url.ToString());
                return false;
            }
        }
    }

}

【问题讨论】:

  • WebView 无法显示 pdf 文件。
  • @greenapps 有没有办法从链接中显示 pdf 文件
  • 飞赞已经告诉过你了。
  • @greenapps 我已经修改了看到 github 的代码。现在我想首先显示网址。然后在 url 中存在另一个 pdf 的 url。我想表明当用户单击该按钮时。我在 Touch 方法上实现了一个布尔值。如果我点击 pdf 的链接,没有任何反应

标签: c# android pdf webview xamarin.android


【解决方案1】:

在下面的链接中提到:

Read this link

您需要使用WebViewRenderer 实现以下代码

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

【讨论】:

  • android_asset 也适用于 url 链接?我需要 Webviewrender 而不是 Activity?
  • @ktina51 这是一个示例网址,您可以自己尝试一下。
  • 对不起,我是 xamarin 的新手。我是否应该在您创建 CustomWebViewRenderer 时为此创建一个新类:WebViewRenderer here
  • @ktina51 是的,你应该去这个链接:developer.xamarin.com/recipes/cross-platform/xamarin-forms/…
  • 但是这个 wensite 适用于 Xamarin.Form。我正在开发原生应用程序
【解决方案2】:

有没有办法从链接中显示 pdf 文件

如前所述,android webview 不支持 pdf 文件。作为一种解决方法,您可以在 android webview 中使用 Google Docs:

  1. 创建一个自定义 webview 客户端并像这样覆盖 ShouldOverrideUrlLoading

    public class MyWebViewClient: WebViewClient
    {
        public override bool ShouldOverrideUrlLoading(WebView view, string url)
        {
            //if PDF file then use google client to show it
            if (url.ToLower().EndsWith(".pdf"))
            {
                var newUrl = "https://docs.google.com/viewer?url=" + url;
                view.LoadUrl(newUrl);
            }
            return true;
        }
    }
    
  2. 使用您的自定义 webview 客户端:

    mWebview.SetWebViewClient(new MyWebViewClient());
    

注意:如果您的 webview 使用 android:layout_height="wrap_content",则需要将其更改为固定 dp,例如 android:layout_height="400dp",否则 webview 将无法正确显示 pdf。

【讨论】:

    猜你喜欢
    • 2019-03-24
    • 1970-01-01
    • 2015-10-11
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 2017-03-07
    相关资源
    最近更新 更多