Reputation: 141
I'm using Xamarin Forms' WebView control to show a PDF, the problem is that this control only renders it for iOS correctly, for Android this does not happen, so I must implement different solutions for each of the platforms, so I'm using the following implementation with pdf.js recipes
My app displays PDFs that are locally in the device, but it is not showing in the customized control, the first question I have is ... Can I pass the file path to the WebView so that I can visualize it? in the following way ...
the previous thing to bindar the property PDF to the customized control of the following form
<local:CustomWebView Uri="{Binding PDF}"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand" />
It is worth mentioning that introducing a PDF in the content folder of the Android project in the following way
and then batch it in the following way in my XAML view, it works !!!
<local:CustomWebView Uri="CV.pdf"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand" />
The way to pass the path to my PDF property from my ViewModel is the following ...
ViewModel.CS:
#region Constructor
public VisorArchivosViewModel(Evidencia evidencia)
{
navigationService = new NavigationService();
this.evidencia = evidencia;
if (evidencia != null)
{
PDF = evidencia.Path;
}
}
#endregion
I know that my question is basic, but how can I show a PDF that is stored locally on my device in a WebView?
ANY HELP FOR ME¿?
Upvotes: 1
Views: 2643
Reputation: 7179
You need to customize your custom renderer, to provide the local path of the 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);
}
}
}
}
}
Upvotes: 1