在android下载PDF文件



我必须从webview下载pdf/txt文件,我尝试了这个代码,但什么都没有发生,有什么建议吗?

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

您可以使用自定义渲染器通过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);
}
}
}