How to load PDF in Xamarin Forms

前端 未结 3 1383
陌清茗
陌清茗 2020-12-09 21:07

I have a Xamarin Forms app where I want to open a locally stored PDF. I don\'t need to load them within the app, I\'m fine with shelling out to the device\'s default documen

3条回答
  •  醉梦人生
    2020-12-09 21:52

    I had to do something and solve it using a DependencyService . You can use it to open the pdf depending on each platform

    I show you an example of how to solve it on Android :

    IPdfCreator.cs:

    public interface IPdfCreator
        {
            void ShowPdfFile();
        }
    

    MainPage.cs:

    private void Button_OnClicked(object sender, EventArgs e)
    {
        DependencyService.Get().ShowPdfFile();
    }
    

    PdfCreatorAndroid.cs

    [assembly: Dependency(typeof(PdfCreatorAndroid))]
    namespace Example.Droid.DependecyServices
    {
        public class PdfCreatorAndroid : IPdfCreator
        {
    
            public void ShowPdfFile()
            {
                var fileLocation = "/sdcard/Template.pdf";
                var file = new File(fileLocation);
    
                if (!file.Exists())
                    return;
    
                var intent = DisplayPdf(file);
                Forms.Context.StartActivity(intent);
            }
    
            public Intent DisplayPdf(File file)
            {
                var intent = new Intent(Intent.ActionView);
                var filepath = Uri.FromFile(file);
                intent.SetDataAndType(filepath, "application/pdf");
                intent.SetFlags(ActivityFlags.ClearTop);
                return intent;
            }
        }
    }
    

    Result: http://i.stack.imgur.com/vrwzt.png

提交回复
热议问题