Show a pdf into a webview from a link inside that

2019-08-21 08:10发布

问题:

In my app I have implemented a webview to show a website link into that webview. Now that website has a button that contains a pdf file link. If I click on that button on website it shows a pdf file on the web. But if I try to open it into the webview in my app, nothing happens. I am very new in Xamarin android. I could not find any suitable way to that. Here is my code to show the website into the webview.

I want to relod the pdf when click on link from the website. But the result is same as before

Modified Code

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

}

回答1:

Mentioned in the link below:

Read this link

You will need to implement following code using 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))));
            }
        }
    }
}


回答2:

is there any way to show pdf file from a link

As discussed android webview doesn't support pdf files. As a workaround, you can use Google Docs in android webview:

  1. Create a custom webview client and override ShouldOverrideUrlLoading like this:

    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. Use your custom webview client:

    mWebview.SetWebViewClient(new MyWebViewClient());
    

Notes: If you use android:layout_height="wrap_content" for your webview, you need to change it to a fixed dp like android:layout_height="400dp", otherwise the webview won't show pdf correctly.