首页 > 解决方案 > download pdf files on android

问题描述

I have to download pdf / txt files from the webview, I tried this code but nothing still happens, any advice?

xaml

<WebView x:Name="wvSite"
                     VerticalOptions="FillAndExpand" 
                     HeightRequest="1330"  
                     Navigating="webOnNavigating"/>

CS

public partial class Documenti : ContentPage
{
    public Documenti()
    {
        InitializeComponent();
        wvSite.Source = App.URL + "Documenti.aspx";
    }

protected void webOnNavigating(object sender, WebNavigatingEventArgs e)
    {
        if (e.Url.Contains(".pdf"))
        {
            // Retrieving the URL
            var pdfUrl = new Uri(e.Url);

            // Open PDF URL with device browser to download
            Device.OpenUri(pdfUrl);

            // Cancel the navigation on click actions (retains in the same page.)
            e.Cancel = true;
        }
    }

标签: pdfxamarinxamarin.formsxamarin.android

解决方案


您可以使用自定义渲染器通过 WebView 下载文件。

 [assembly: ExportRenderer(typeof(Xamarin.Forms.WebView), 
typeof(UpgradeWebViewRenderer))]
namespace App8.Droid
{
public class UpgradeWebViewRenderer : ViewRenderer<Xamarin.Forms.WebView, global::Android.Webkit.WebView>
{
    public UpgradeWebViewRenderer(Context context) : base(context)
    {


    }

    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
    {
        base.OnElementChanged(e);

        if (this.Control == null)
        {
            var webView = new global::Android.Webkit.WebView(this.Context);
            webView.SetWebViewClient(new WebViewClient());
            webView.SetWebChromeClient(new WebChromeClient());
            WebSettings webSettings = webView.Settings;
            webSettings.JavaScriptEnabled = true;
            webView.SetDownloadListener(new CustomDownloadListener());
            this.SetNativeControl(webView);
            var source = e.NewElement.Source as UrlWebViewSource;
            if (source != null)
            {
                webView.LoadUrl(source.Url);
            }
        }
    }
}

public class CustomDownloadListener : Java.Lang.Object, IDownloadListener
{
    public void OnDownloadStart(string url, string userAgent, string contentDisposition, string mimetype, long contentLength)
    {
        DownloadManager.Request request = new DownloadManager.Request(Android.Net.Uri.Parse(url));
        request.AllowScanningByMediaScanner();
        request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
        request.SetDestinationInExternalFilesDir(Forms.Context, Android.OS.Environment.DirectoryDownloads, "hello.jpg");
        DownloadManager dm = (DownloadManager)Android.App.Application.Context.GetSystemService(Android.App.Application.DownloadService);
        dm.Enqueue(request);
    }
}

}

推荐阅读