Forum Xamarin.Android

How to open Pdf in imagebutton?

CastielTRCastielTR Member ✭✭

I was tried many times for open with pdf viewer but ı can't add in library, actually how to open a pdf when I click an image button ?

Best Answer

  • CastielTRCastielTR Member ✭✭
    Accepted Answer

    @CastielTR said:
    I tried to try open pdf in local file, this is to difficult for me, I want to learn How to open pdf(html) in a activity class ?

    I finish this problem finaly with webview, thanks.(google drive with pdf)

Answers

  • jezhjezh Member, Xamarin Team Xamurai
    edited March 4

    You can try the followig code

       public void OpenFile(string filePath)
        {
            var bytes = File.ReadAllBytes(filePath);
    
            //Copy the private file's data to the EXTERNAL PUBLIC location
            string externalStorageState = global::Android.OS.Environment.ExternalStorageState;
            string application = "";
    
            string extension = System.IO.Path.GetExtension (filePath);
    
            switch (extension.ToLower()) {
            case ".doc":
            case ".docx":
                application = "application/msword";
                break;
            case ".pdf":
                application = "application/pdf";
                break;
            case ".xls":
            case ".xlsx":
                application = "application/vnd.ms-excel";
                break;
            case ".jpg":
            case ".jpeg":
            case ".png":
                application = "image/jpeg";
                break;
            default:
                application = "*/*";
                break;
            }
            var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/report" + extension;
            File.WriteAllBytes(externalPath, bytes);
    
            Java.IO.File file = new Java.IO.File(externalPath); 
            file.SetReadable(true);
            //Android.Net.Uri uri = Android.Net.Uri.Parse("file://" + filePath);
            Android.Net.Uri uri =  Android.Net.Uri.FromFile(file);
            Intent intent = new Intent(Intent.ActionView);
            intent.SetDataAndType(uri, application);
            intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
    
            try
            {
                Xamarin.Forms.Forms.Context.StartActivity(intent);
            }
            catch (Exception)
            {
                Toast.MakeText(Xamarin.Forms.Forms.Context, "No Application Available to View PDF", ToastLength.Short).Show();
            }
        }
    

    Refer: https://forums.xamarin.com/discussion/39912/open-pdf-in-android-default-pdf-reader


    Xamarin forums are migrating to a new home on Microsoft Q&A!
    We invite you to post new questions in the Xamarin forums’ new home on Microsoft Q&A!
    For more information, please refer to this sticky post.

  • CastielTRCastielTR Member ✭✭

    Too many errors, no information on how to use this code. Please provide a solution regarding xamarin forms. This solution is not android, It is for Xamarin forms.

  • jezhjezh Member, Xamarin Team Xamurai

    Please provide a solution regarding xamarin forms.

    You can follow the following steps including in link: https://github.com/xamarin/docs-archive/tree/master/Recipes/xamarin-forms/Controls/display-pdf .

    Above method could display a PDF file in the WebView control on each platform:

    1.Creating the Custom WebView Control

    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); }
        }
    }
    

    2.Consuming the Custom Control

    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:local="clr-namespace:DisplayPDF;assembly=DisplayPDF"
                 x:Class="DisplayPDF.WebViewPage"
                 Padding="0,20,0,0">
        <ContentPage.Content>
            <local:CustomWebView Uri="BookPreview2-Ch18-Rel0417.pdf" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" />
        </ContentPage.Content>
    </ContentPage>
    
    

    3.Creating the Custom Renderer on 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))));
                }
            }
        }
    }
    
  • CastielTRCastielTR Member ✭✭

    When ı create a WebView class, the get-set commands are not see by IDE, I add already the library tools. and BindableProperty are too.

  • CastielTRCastielTR Member ✭✭

    I tried to try open pdf in local file, this is to difficult for me, I want to learn How to open pdf(html) in a activity class ?

  • jezhjezh Member, Xamarin Team Xamurai
  • CastielTRCastielTR Member ✭✭
    Accepted Answer

    @CastielTR said:
    I tried to try open pdf in local file, this is to difficult for me, I want to learn How to open pdf(html) in a activity class ?

    I finish this problem finaly with webview, thanks.(google drive with pdf)

Sign In or Register to comment.