我正在使用 Xamarin Forms 的 WebView 控件来显示 PDF,问题是这个控件只为 iOS 正确呈现它,对于 Android 这不会发生,所以我必须为每个平台实现不同的解决方案,所以我使用 pdf.js recipes 的以下实现
我的应用程序显示设备本地的 PDF,但它没有显示在自定义控件中,我的第一个问题是......我可以将文件路径传递给 WebView 以便我可以可视化它吗?通过以下方式...
上一件事将属性 PDF 绑定(bind)到以下表单的自定义控件
<local:CustomWebView Uri="{Binding PDF}"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand" />
值得一提的是,在Android项目的content文件夹中引入一个PDF的方式如下
然后在我的 XAML View 中按以下方式对其进行批处理,它可以工作!!!
<local:CustomWebView Uri="CV.pdf"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand" />
从我的 ViewModel 传递我的 PDF 属性的路径的方法如下......
View 模型.CS:
#region Constructor
public VisorArchivosViewModel(Evidencia evidencia)
{
navigationService = new NavigationService();
this.evidencia = evidencia;
if (evidencia != null)
{
PDF = evidencia.Path;
}
}
#endregion
我知道我的问题是基本的,但是如何在 WebView 中显示本地存储在我的设备上的 PDF?
对我有什么帮助吗?
最佳答案
您需要自定义自定义渲染器,以提供 PDF 的本地路径。
[assembly: ExportRenderer(typeof(CustomWebView), typeof(CustomWebViewRenderer))]
{
public class CustomWebViewRenderer : WebViewRenderer
{
public CustomWebViewRenderer(Context context) : base(context) { }
protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged(e);
if (e.NewElement != null)
{
var customWebView = Element as CustomWebView;
if (File.Exists(customWebView.Uri))
{
Control.Settings.AllowUniversalAccessFromFileURLs = true;
var finalStr = string.Format(
"file:///android_asset/pdfjs/web/viewer.html?file={0}",
string.Format(
"file:///{0}",
WebUtility.UrlEncode(customWebView.Uri)
)
);
Control.LoadUrl(finalStr);
}
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (e.PropertyName == "Uri")
{
var customWebView = Element as CustomWebView;
if (File.Exists(customWebView.Uri))
{
Control.Settings.AllowUniversalAccessFromFileURLs = true;
var finalStr = string.Format(
"file:///android_asset/pdfjs/web/viewer.html?file={0}",
string.Format(
"file:///{0}",
WebUtility.UrlEncode(customWebView.Uri)
)
);
Control.LoadUrl(finalStr);
}
}
}
}
}
关于c# - 如何在 Xamarin Forms 中使用 pdf.js 查看 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55224487/