【问题标题】:Unable to load a pdf file which has special characters(!@#) in file path. Webview Xamarin forms无法加载文件路径中包含特殊字符 (!@#) 的 pdf 文件。 Webview Xamarin 表单
【发布时间】:2020-05-29 08:27:08
【问题描述】:

我正在通过 Web 视图在 Xamarin 中加载 pdf 文件。当文件路径中有特殊字符时,不会加载pdf文件。

下面是代码。

如果(e.NewElement 是 PDFView pdfWebView) {

            this.Control.Settings.JavaScriptEnabled = true;
            this.Control.Settings.AllowFileAccess = true;
            this.Control.Settings.AllowUniversalAccessFromFileURLs = true;
            Control.LoadUrl($"file:///android_asset/pdfjs/web/viewer.html?file=file://{pdfWebView.Uri}");
        }

【问题讨论】:

    标签: xamarin webview


    【解决方案1】:

    您没有指定您正在使用什么,但从文件路径来看,我可以安全地假设您正在使用PDF.js。如果是这种情况,那么您需要对文件名进行 URL 编码。 根据FAQ page

    您可以修改 web/app_options.js 文件中的 defaultUrl 应用选项,也可以将 ?file= 查询字符串附加到查看器 URL,例如http://mozilla.github.com/pdf.js/web/viewer.html?file=compressed.tracemonkey-pldi-09.pdf。在后一种情况下,PDF 路径/URL 必须使用 encodeURIComponent() 进行编码

    因此,您只需在路径上调用encodeURIComponent()

    编辑:您必须使用 js 函数 encodeURIComponent() 对 URI 进行编码,因为 js 函数对路径的编码方式与 C# 对路径的编码方式存在一些差异。

    例如比较WebUtility.UrlEcode docs 和encodeURIComponent docs,我们可以看到大部分转义是相似的。被转义的是:

    encodeURIComponent() 转义所有字符,除了: A-Z a-z 0-9 - _ 。 ! ~ * ' ( )

    到目前为止一切顺利。不幸的是,这两种方法都以不同的方式转义“”(空格)符号。

    C# 的方法UrlEncode 这样做:

    每个 ' '(空格)字符都转换为 +(加号)字符。

    JS 的函数encodeURIComponent 这样做:

    console.log(encodeURI("ABC abc 123")); // ABC%20abc%20123(空格被编码为%20)

    【讨论】:

    • 谢谢米哈伊尔。编码不起作用。你能分享任何带有源代码的例子吗?
    • 你是调用了JS函数encodeURIComponent()还是自己用C#编码的?
    • 我尝试了以下方法。 var EncodingStr = WebUtility.UrlEncode($"file://{pdfWebView.Uri}"); Control.LoadUrl($"file:///android_asset/pdfjs/web/viewer.html?{EncodingStr}");
    • 就像我说的,你必须使用 JS 的函数进行编码 - encodeURIComponent。不幸的是,C# 的UrlEncode 在这里不起作用。您总是可以在 C# 中对其进行编码,然后将其调整为 JS 所期望的。我已经相应地更新了我的答案。
    【解决方案2】:
    string path = "/path/to/local/file"
    Java.IO.File myFile = new Java.IO.File(path);
    Java.Net.URL url = myFile.ToURI().ToURL();
    string urlStr = string.Format("file:///android_asset/pdfjs/web/viewer.html?file={0}", url, WebUtility.UrlEncode(customWebView.Uri));
    urlStr = urlStr.Replace("&", "%26");
    Control.LoadUrl(urlStr);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      相关资源
      最近更新 更多