Reputation: 325
I download a pdf stream from my server. In my app I save the bytearray to a the local folder as pdf. But when I open it in the webview, it just shows a white page.
I followed this example: https://developer.xamarin.com/recipes/cross-platform/xamarin-forms/controls/display-pdf.
Here is customwebview in my xaml:
<local:CustomWebView x:Name="customView" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" />
Here is my code of the custom view:
public class CustomWebView : WebView
{
public static readonly BindableProperty UriProperty = BindableProperty.Create(propertyName: "Uri",
returnType: typeof(string),
declaringType: typeof(CustomWebView),
defaultValue: default(string));
public string Uri
{
get { return (string)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
}
This is my method to retrieve the pdf byte array and store it locally:
private async void ReadPDF()
{
var response = CommonLibrary.Helpers.HTTPClientHelper.DownloadPDF(AccountBL.AccessToken, APISettings.APIURI("api/booking/pdf"));
var streamContent = response.Content as System.Net.Http.StreamContent;
var bytes = CommonLibrary.Helpers.FileHelper.ReadBytes(await streamContent.ReadAsStreamAsync());
var dir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fileName = "test.pdf";
CommonLibrary.Helpers.FileHelper.WriteFileFromByteArray(bytes, dir, fileName);
customView.Uri = System.IO.Path.Combine(dir, fileName);
}
Am I missing something?
Upvotes: 2
Views: 12739
Reputation: 142
Following approach will allow you to view pdf in xamarin forms. If you are trying to open one from azure blob or you have valid URl.
WebView webView = new WebView();
var page = new ContentPage();
webView.Source = "https://docs.google.com/viewer?url=http://yourpdfurl.pdf";
page.Content = webView;
Navigation.PushModalAsync(page);
Upvotes: 2
Reputation: 5768
If I remember correctly, you can display a "remote" PDF in a webview on iOS. With Android there are some problems. I suggest to take a look to this repo OpenPDF. I use a CustomRenderer and a google tool to display the PDF. I have had some problems with some Android version... but you can take a look.(here a blog)
Otherwise there is @AdamPedley suggestion to use PDF JS Viewer Adam Pedley The code is here.
This is the CustomRenderer for Android
[assembly: ExportRenderer (typeof(CustomWebView), typeof(CustomWebViewRenderer))]
namespace DisplayPDF.Droid
{
public class CustomWebViewRenderer : WebViewRenderer
{
protected override void OnElementChanged (ElementChangedEventArgs<WebView> e)
{
base.OnElementChanged (e);
if (e.NewElement != null) {
var customWebView = Element as CustomWebView;
Control.Settings.AllowUniversalAccessFromFileURLs = true;
Control.LoadUrl (string.Format ("file:///android_asset/pdfjs/web/viewer.html?file={0}", string.Format ("file:///android_asset/Content/{0}", WebUtility.UrlEncode (customWebView.Uri))));
}
}
}
}
Upvotes: 4