简体   繁体   English

如何在 Xamarin Forms 的默认应用程序中打开 PDF 或 TXT 文件

[英]How to open PDF or TXT file in default app on Xamarin Forms

I am going to open document using default app in Xamarin Forms.我将使用 Xamarin Forms 中的默认应用程序打开文档。 I tried already this approach but it doesn't work for me and I am not sure what is the reason.我已经尝试过这种方法,但它对我不起作用,我不确定是什么原因。

Device.OpenUri(new Uri(FILE_PATH));

Please give me great solution if anyone knows how to handle it.如果有人知道如何处理它,请给我很好的解决方案。 Thanks.谢谢。

You can use DependencyService to implement this from each platform.您可以使用DependencyService从每个平台实现这一点。 Firstly, create a interface from PCL for example like:首先,从 PCL 创建一个接口,例如:

public interface IFileViewer
{
    void ShowPDFTXTFromLocal(string filename);
}

Then for Android platform, create a class to implement this interface:然后对于Android平台,创建一个类来实现这个接口:

[assembly: Xamarin.Forms.Dependency(typeof(FileViewer))]

namespace NameSpace.Droid
{
    public class FileViewer : IFileViewer
    {
        public void ShowPDFTXTFromLocal(string filename)
        {
            string dirPath = Xamarin.Forms.Forms.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryDocuments).Path;
            var file = new Java.IO.File(dirPath, System.IO.Path.Combine(dirPath, filename));

            if (file.Exists())
            {
                Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
                {
                    var uri = Android.Net.Uri.FromFile(file);
                    Intent intent = new Intent(Intent.ActionView);
                    var mimetype = MimeTypeMap.Singleton.GetMimeTypeFromExtension(MimeTypeMap.GetFileExtensionFromUrl((string)uri).ToLower());
                    intent.SetDataAndType(uri, mimetype);
                    intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);

                    try
                    {
                        Xamarin.Forms.Forms.Context.StartActivity(intent);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.ToString());
                    }
                });
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("file not found");
            }
        }
    }
}

This is a example only works for the files which be placed in GetExternalFilesDir(Android.OS.Environment.DirectoryDocuments) , if your files are in other place, you will need to modify the code.此示例仅适用于放置在GetExternalFilesDir(Android.OS.Environment.DirectoryDocuments)的文件,如果您的文件位于其他位置,则需要修改代码。

I implemented below code and worked perfectly.我实现了下面的代码并且工作得很好。 I hope that this code will help others.我希望这段代码能帮助其他人。

var PreviewController = UIDocumentInteractionController.FromUrl(NSUrl.FromFilename(filePath));
PreviewController.Delegate = new UIDocumentInteractionControllerDelegateClass(UIApplication.SharedApplication.KeyWindow.RootViewController);
Device.BeginInvokeOnMainThread(() =>
{
    PreviewController.PresentPreview(true);
});

public class UIDocumentInteractionControllerDelegateClass : UIDocumentInteractionControllerDelegate
{
    UIViewController ownerVC;

    public UIDocumentInteractionControllerDelegateClass(UIViewController vc)
    {
        ownerVC = vc;
    }

    public override UIViewController ViewControllerForPreview(UIDocumentInteractionController controller)
    {
        return ownerVC;
    }

    public override UIView ViewForPreview(UIDocumentInteractionController controller)
    {
        return ownerVC.View;
    }
}

2020 update: Xamarin now has a very simple solution for this using Xamarin.Essentials. 2020 年更新:Xamarin 现在使用 Xamarin.Essentials 提供了一个非常简单的解决方案。 You can use a single line of code to open a file in the default application using Launcher.OpenAsync:您可以使用一行代码在默认应用程序中使用 Launcher.OpenAsync 打开文件:

await Launcher.OpenAsync(new OpenFileRequest { File = new ReadOnlyFile(uri) });

Here is some sample code I am using in my app to open PDF files in the default application:这是我在我的应用程序中使用的一些示例代码,用于在默认应用程序中打开 PDF 文件:

private void BtnOpen_Clicked(object sender, EventArgs e)
{
    string filePathAndName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "test.pdf");
    OpenPdf(filePathAndName);
}

public async void OpenPdf(string uri)
{
    await Launcher.OpenAsync(new OpenFileRequest { File = new ReadOnlyFile(uri) });
}

This will work on any platform with no custom renderers needed (as long as you have Xamarin.Essentials added to each project).这将适用于不需要自定义渲染器的任何平台(只要您将 Xamarin.Essentials 添加到每个项目)。 Here is a link to the Microsoft documentation which provides some additional information. 这是指向 Microsoft 文档的链接,其中提供了一些附加信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Xamarin.Forms - 使用默认应用打开文件 - Xamarin.Forms - Open file with default app Xamarin.Forms,如何打开默认图库应用 - Xamarin.Forms, How to open default gallery app Xamarin.Forms 在本地存储中保存文件 (pdf) 并使用默认查看器打开 - Xamarin.Forms save file (pdf) in local storage and open with the default viewer 如何在 Android 中下载并打开 PDF 11 Xamarin Z6450242531912981C3683CAE8 - How to download and open a PDF in Android 11 Xamarin Forms Xamarin Forms:如何从另一个应用程序打开一个应用程序? - Xamarin Forms: How to open an app from another app? 将 PDF 下载为字节流,然后在 Xamarin.Forms 中的默认 Android 应用程序中打开 - Download PDF as byte stream then open in default Android application in Xamarin.Forms Xamarin 表单 - 以流形式打开文件 - Xamarin forms - Open file as stream CrossPlatform Xamarin表单:如何在本地存储中创建PDF文件 - CrossPlatform Xamarin forms : How to create PDF file in local storage 使用默认应用程序的Xamarin Android Open文件在Android 7或更高版本中不起作用 - Xamarin Android Open file using default app not work in Android 7 or above 在 Xamarin.Forms 中创建默认 SMS 应用程序 - Creating Default SMS App in Xamarin.Forms
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM