我试图找到在 xamarin.forms 上显示本地 pdf 文件的方法。 我找到了实现 webview 及其渲染的自定义实现的解决方案:pdf reader
主要代码为:
public class CustomWebView : WebView
{
public static readonly BindableProperty UriProperty = BindableProperty.Create<CustomWebView, string>(p => p.Uri, default(string));
public string Uri
{
get { return (string)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
}
渲染:
[assembly: ExportRenderer (typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace DisplayPDF.iOS
{
public class CustomWebViewRenderer : ViewRenderer<CustomWebView, UIWebView>
{
protected override void OnElementChanged (ElementChangedEventArgs<CustomWebView> e)
{
base.OnElementChanged (e);
if (Control == null) {
SetNativeControl (new UIWebView ());
}
if (e.OldElement != null) {
// Cleanup
}
if (e.NewElement != null) {
var customWebView = Element as CustomWebView;
string fileName = Path.Combine (NSBundle.MainBundle.BundlePath, string.Format ("Content/{0}", WebUtility.UrlEncode (customWebView.Uri)));
Control.LoadRequest (new NSUrlRequest (new NSUrl (fileName, false)));
Control.ScalesPageToFit = true;
}
}
}
}
还有我的页面:
public class WebViewPageCS : ContentPage
{
public WebViewPageCS ()
{
webView = new CustomWebView
{
Uri = "ScalaReference.pdf",
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand
};
}
但是现在我找不到像这篇文章中描述的那样向这个 pdf 文件添加 anchor 的方法:anchor to pdf
我还尝试使用这段代码来评估脚本:
private async void Scroll_Clicked(object sender, EventArgs e)
{
webView.Eval($"window.scrollTo(0, {x});");
}
它适用于默认的 webview,但不适用于自定义的。
也许有人知道滚动/将 anchor 设置为 pdf 并通过 xamarin.forms 链接到此 anchor 的任何其他方法? 谢谢。
最佳答案
it works fine with default webview but not with custom one.
这不是由自定义 webview 引起的,因为渲染器为 Control
创建了一个新的 UIWebview |在 CustomWebViewRenderer
,看这段代码部分:
if (Control == null) {
SetNativeControl (new UIWebView ());
}
所以,执行 webView.Eval($"window.scrollTo(0, {x});");
时它不起作用, 因为这个 webview 实际上不是 UIWebview。
解决方案
在 CustomWebView 中创建 BindableProperty
public static readonly BindableProperty AnchorProperty = BindableProperty.Create<CustomWebView, float>(p => p.Anchor, default(float));
public float Anchor
{
get { return (float)GetValue(AnchorProperty); }
set { SetValue(AnchorProperty, value); }
}
在页面中触发
private void Scroll_Clicked(object sender, System.EventArgs e)
{
webview.Anchor = 200;
}
获取渲染器中的值并使 webview 滚动。
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if(e.PropertyName is "Anchor")
{
var customWebView = Element as CustomWebView;
float anchor = customWebView.Anchor;
Control.ScrollView.ContentOffset = new CoreGraphics.CGPoint(0, anchor);
}
}
关于c# - 用于阅读 pdf 的自定义 Xamarin.Forms.WebView。用 anchor 滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50584588/