繁体   English   中英

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

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

我将使用 Xamarin Forms 中的默认应用程序打开文档。 我已经尝试过这种方法,但它对我不起作用,我不确定是什么原因。

Device.OpenUri(new Uri(FILE_PATH));

如果有人知道如何处理它,请给我很好的解决方案。 谢谢。

您可以使用DependencyService从每个平台实现这一点。 首先,从 PCL 创建一个接口,例如:

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

然后对于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");
            }
        }
    }
}

此示例仅适用于放置在GetExternalFilesDir(Android.OS.Environment.DirectoryDocuments)的文件,如果您的文件位于其他位置,则需要修改代码。

我实现了下面的代码并且工作得很好。 我希望这段代码能帮助其他人。

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 年更新:Xamarin 现在使用 Xamarin.Essentials 提供了一个非常简单的解决方案。 您可以使用一行代码在默认应用程序中使用 Launcher.OpenAsync 打开文件:

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

这是我在我的应用程序中使用的一些示例代码,用于在默认应用程序中打开 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) });
}

这将适用于不需要自定义渲染器的任何平台(只要您将 Xamarin.Essentials 添加到每个项目)。 这是指向 Microsoft 文档的链接,其中提供了一些附加信息。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM