Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
399 views
in Technique[技术] by (71.8m points)

c# - Show a pdf into a webview from a link inside that Website Xamarin android

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

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...