【问题标题】:Xamarin Android WebView download inline pdf contentXamarin Android WebView 下载内联 pdf 内容
【发布时间】:2018-07-15 23:21:45
【问题描述】:

Android 专家...我很困惑。我在 Forms 应用程序中嵌入了一个 WebView,该应用程序还为其实现了一个自定义渲染器(用于 WebView)。

我正在打包一个基本的 Web 应用程序 (SAP Fiori),在该应用程序中,它有一个工资报表部分,用户可以在其中查看他们的工资单。在该页面上,有一个按钮可将工资单下载为 PDF。

在我的应用程序的 iOS 中,这一切都是标准的,即 PDF 打开并在浏览器中查看。在 Android 和 iOS 上,任何浏览器(如 Chrome 或 Safari)都可以正常工作。

在我的 Android 应用程序中,单击“以 PDF 格式打开”按钮不会产生任何结果,前端不会发生任何事情,但在应用程序本身内,已实现的 DownloadListener 方法被触发...

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

        Control.Settings.AllowUniversalAccessFromFileURLs = true;

        Control.SetWebViewClient(new MySAPWebViewClient(Context));
        Control.SetDownloadListener(new MySAPDownloadListener());
    }

public class MySAPDownloadListener : Java.Lang.Object, IDownloadListener
{
    public new void Dispose() { }

    public void OnDownloadStart(string url, string userAgent, string contentDisposition, string mimetype, long contentLength)
    {
        System.Diagnostics.Debug.WriteLine("Url = " + url);
        System.Diagnostics.Debug.WriteLine("Content Disposition = " + contentDisposition);
        System.Diagnostics.Debug.WriteLine("Mime Type = " + mimetype);
    }
}

这些是主要的 DownloadEventArgs 值...

url = "https://organisation.com/sap/opu/odata/sap/HCM_MY_PAYSTUBS_SRV/PDFPaystubs(SEQUENCENUMBER=189,PersonnelAssignment='00044411')/$value"
contentDisposition = "inline; filename=Paystub_01.31.2018.pdf"
mimetype = "application/pdf"

...现在,在那个 url 后面,有一段 javascript 生成动态 PDF,所以它没有存储在服务器上的任何地方,这就是我似乎遇到问题的地方。

我在网上阅读的所有内容都说使用 HttpClient 将 PDF 的内容下载到文件然后打开它。但是,如果我将该 URL 传递给 HttpClient,我不会得到 PDF 数据,而是得到 HTML 文本。

我在 StackOverflow 上尝试过 GoogleDocs 和许多其他链接,但无论我做什么,该 URL 都会返回 HTML 文本,而不是 PDF 文档的内容。

我也几乎无法控制 SAP 为我提供的功能,因此更改服务器端不太可能。

任何帮助将不胜感激。

【问题讨论】:

  • 我会查看您从浏览器执行此操作时发送的所有请求参数,并确保您在请求中尽可能地复制它们
  • 您好,您找到解决方案了吗?我也在为此苦苦挣扎。
  • @Vijay,不,对不起!从那个项目开始,我已经很好地、真正地开始了,但我从来没有克服过它。我最终隐藏了使用 WebView 中的一些 JavaScript 调用调用的按钮。

标签: android forms pdf xamarin webview


【解决方案1】:

很遗憾,由于某种原因,Android WebView 无法显示 PDF 文件。 因此,如果使用 WebView 对您来说至关重要,那么只有一种选择 - 使用 Google Docs Viewer。但它仅适用于可通过公共 URL 获得的 PDF。它看起来像这样:

 WebView view=(WebView)findViewById(R.id.webView);
 view.setWebViewClient(new WebViewClient());
 String url=getIntent().toString("value1");
 String URL="https://docs.google.com/viewer?url="+url; 
 view.loadUrl(Url);

如果使用 WebView 不是那么重要,你可以使用:

  1. 一些第三方库显示 PDF
  2. 调用 Intent 以通过其他应用显示 PDF
  3. 如果您使用 API 级别 21 及更高级别 - 您可以使用 Android PdfRenderer

希望对你有帮助

【讨论】:

  • 是的,感谢您的提醒,但已经尝试过 Google Docs。鉴于 html 是从 url 返回的,而不是真正的 pdf,Google Docs 为我提供了格式精美的 html。 :-) 。非常令人沮丧。至于查看器,我仍然没有接近,因为它再次返回 html,而不是 pdf 数据流。感谢您的帮助。
【解决方案2】:

您可以通过两种解决方案做到这一点:

解决方案 1: 在系统默认浏览器中打开 URL。

private async Task MWebview_Download(object sender, DownloadEventArgs e)
{
    await Launcher.OpenAsync(e.Url);               
}

解决方案 2 使用 HttpClient 下载。

    private async void MWebview_Download(object sender, DownloadEventArgs e)
    {
        string fileName = GetFileName(e);

        Device.BeginInvokeOnMainThread(() =>
        {
            Toast.MakeText(MainActivity.Instance, "Downloading File...", ToastLength.Long).Show();
        });


        await DownloadPdfFile(e, fileName);
    }

    private async Task DownloadPdfFile(DownloadEventArgs e, string fileName)
    {
        try
        {
            //Bypass the certificate 
            HttpClientHandler clientHandler = new HttpClientHandler();
            clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };

            // Getting Cookie
            String cookies = CookieManager.Instance.GetCookie(e.Url);

            var client = new HttpClient(clientHandler);
            var httpRequestMessage = new HttpRequestMessage
            {
                Method = HttpMethod.Get,
                RequestUri = new Uri(e.Url),
                Headers = {
                { HttpRequestHeader.TransferEncoding.ToString(), "binary" },
                { HttpRequestHeader.ContentLength.ToString(), e.ContentLength+"" },
                { HttpRequestHeader.ContentType.ToString(), "application/pdf" },
                {HttpRequestHeader.Cookie.ToString(),cookies },
            },
            };

            // Api Call
            var response = await client.SendAsync(httpRequestMessage);

            // Read content as Byte[]
            var bytes = response.Content.ReadAsByteArrayAsync().Result;

            // Save to Local DB
            var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
            var filePath = Path.Combine(documentsPath, fileName);

            // convert byte to stream
            MemoryStream stream = new MemoryStream(bytes);

            // Write file
            SaveAndView(fileName, "application/pdf", stream);

        }
        catch (Exception ee)
        {
            Toast.MakeText(MainActivity.Instance, "Failed !!", ToastLength.Long).Show();
        }
    }

    public void SaveAndView(string fileName, String contentType, MemoryStream stream)
    {
        string exception = string.Empty;
        string root = null;

        if (ContextCompat.CheckSelfPermission(MainActivity.Instance, Manifest.Permission.WriteExternalStorage) != Permission.Granted)
        {
            ActivityCompat.RequestPermissions((Activity)MainActivity.Instance, new String[] { Manifest.Permission.WriteExternalStorage }, 1);
        }

        if (Android.OS.Environment.IsExternalStorageEmulated)
        {
            root = Android.OS.Environment.ExternalStorageDirectory.ToString();
        }
        else
            root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);

        Java.IO.File myDir = new Java.IO.File(root + "/PDFFiles");
        myDir.Mkdir();

        Java.IO.File file = new Java.IO.File(myDir, fileName);

        if (file.Exists()) file.Delete();

        try
        {
            FileOutputStream outs = new FileOutputStream(file);
            outs.Write(stream.ToArray());

            outs.Flush();
            outs.Close();
        }
        catch (Exception e)
        {
            exception = e.ToString();
        }

        if (file.Exists() && contentType != "application/html")
        {
            string extension = MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
            string mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
            Intent intent = new Intent(Intent.ActionView);
            intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
            Android.Net.Uri path = FileProvider.GetUriForFile(MainActivity.Instance, Android.App.Application.Context.PackageName + ".provider", file);
            intent.SetDataAndType(path, mimeType);
            intent.AddFlags(ActivityFlags.GrantReadUriPermission);

            MainActivity.Instance.StartActivity(Intent.CreateChooser(intent, "Choose App"));
        }

    }

注意:确保处理 FileProvider:

 **Changes in Manifest file:** 

   - Add android:requestLegacyExternalStorage="true" in application tag
   
   - Add between application tag

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false" android:grantUriPermissions="true">
          <meta-data
             android:name="android.support.FILE_PROVIDER_PATHS"
             android:resource="@xml/file_paths" />
    </provider>

在 Xamarin.Android 项目的 Resources 文件夹内的 xml 文件夹中添加 file_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
   <external-files-path name="my_images" path="Pictures" />
   <external-files-path name="my_movies" path="Movies" />
   <external-path name="external_files" path="."/>
</paths>     

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    • 2017-04-08
    • 1970-01-01
    相关资源
    最近更新 更多