pdf - 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;
}
}
解决方案
您可以使用自定义渲染器通过 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);
}
}
}
推荐阅读
- python - 在 Ansible 模块中,python 日志记录模块写入到哪里?
- python - 无论做出什么改变,准确率和 F1 分数都是 100%
- python - 为 dev_appserver 导入 python 模块的正确方法是什么?
- gradle-kotlin-dsl - 在不同模块的测试中使用测试包中的代码
- java - 具有 CompletableFuture 的 Java 8 线程:suppletAsync() 后关闭?
- flutter - 如何将 Onpressed 函数添加到列表的每个值
- apache-kafka - 将 kafka-console-producer.sh 运行到另一台服务器
- c# - 如何创建下面描述的涉及列表和数组的方法
- java - 如何将我的 ListView 适配器转换为 RecyclerView 适配器?
- python - 在 Python 中使用带有请求的证书