【问题标题】:How to open PDF file in xamarin forms如何以 xamarin 表单打开 PDF 文件
【发布时间】:2021-09-28 11:21:30
【问题描述】:

我以 byte[] 格式下载了一个 PDF 文件,并使用 File.WriteAllBytes(path, response); 将其保存到内部存储中。

现在无法从 android 模拟器访问它,我如何将它保存在下载文件夹中?我需要什么才能从安装在模拟器中的 pdf 阅读器打开它?

【问题讨论】:

  • 这能回答你的问题吗? Xamarin.Forms save file (pdf) in local storage and open with the default viewer 在提出新问题之前,请先对网站进行一些基本搜索以查找现有帖子。
  • 我在搜索,你引用的线程是特定于 android 的,对我不起作用。我需要一些作为多平台的东西
  • 您的帖子说 无法从 Android 模拟器访问它,这是 Android 特有的。我链接的帖子回答了您提出的问题。
  • 标题说的是xamarin forms,我只是在android模拟器上做个例子

标签: xamarin.forms


【解决方案1】:

如何将其保存在下载文件夹中?

对于android,您可以通过以下路径将pdf文件保存在download folder

  string rootPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);

对于ios,使用this directory存储用户文档和应用数据文件。

var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);

关于在Anaroid中打开pdf,可以使用以下代码:

 public void openpdf()
    {
        string path = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads, "file.pdf");        
        // Get the uri for the saved file
        Android.Net.Uri file = Android.Support.V4.Content.FileProvider.GetUriForFile(MainActivity.mactivity, MainActivity.mactivity.PackageName + ".fileprovider", new Java.IO.File(path));
        Intent intent = new Intent(Intent.ActionView);
        intent.SetDataAndType(file, "application/pdf");
        intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask | ActivityFlags.GrantReadUriPermission | ActivityFlags.NewTask|ActivityFlags.NoHistory);
       
        try
        {
            MainActivity.mactivity.ApplicationContext.StartActivity(intent);              
        }
        catch (Exception)
        {
            Toast.MakeText(Xamarin.Forms.Forms.Context, "No Application Available to View PDF", ToastLength.Short).Show();
        }
    }

您需要在AndroidMainfeast.xml中添加权限WRITE_EXTERNAL_STORAGE和READ_EXTERNAL_STORAGE,然后您还需要在Android 6.0中进行Runtime Permission Checks。

private void checkpermission()
    {
        if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.WriteExternalStorage) == (int)Permission.Granted)
        {
            // We have permission, go ahead and use the writeexternalstorage.
        }
        else
        {
            // writeexternalstorage permission is not granted. If necessary display rationale & request.
            ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.WriteExternalStorage }, 1);
        }
        if (ContextCompat.CheckSelfPermission(this, Manifest.Permission.ReadExternalStorage) == (int)Permission.Granted)
        {
            // We have permission, go ahead and use the ReadExternalStorage.
        }
        else
        {
            // ReadExternalStorage permission is not granted. If necessary display rationale & request.
            ActivityCompat.RequestPermissions(this, new String[] { Manifest.Permission.ReadExternalStorage }, 1);
        }
    }

还在 AndroidManifest.xml 文件中添加一个提供程序:

    <application android:label="PdfSample.Android">
<provider android:name="android.support.v4.content.FileProvider" android:authorities="com.companyname.fileprovider" android:exported="false" android:grantUriPermissions="true">
  <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths"></meta-data>
</provider>
</application>

并在 Resources/xml/file_paths.xml 中添加外部路径

<external-path name="external_files" path="."/>

MainActivity.mactivity 是 MainActivity.cs 中的静态属性:

 public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    public static MainActivity mactivity;
    protected override void OnCreate(Bundle savedInstanceState)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;

        base.OnCreate(savedInstanceState);

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
        mactivity = this;

关于在ios中打开pdf,大家可以看看:

How to view PDF file using Xamarin Forms

更新:

我的回答也是使用DependencyService,你可以在共​​享项目中创建iterface。

public interface Iopenpdf
{
     void openpdf();
}

在Android平台,实现这个接口。

[assembly: Xamarin.Forms.Dependency(typeof(openpdfhandle))]
namespace PdfSample.Droid
{
class openpdfhandle : Iopenpdf
{
    public void openpdf()
    {
        string path = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads, "file.pdf");
        //string path = Path.Combine(Android.App.Application.Context.GetExternalFilesDir(Environment.DirectoryDownloads).ToString(), "file.pdf");          
        // Get the uri for the saved file
        Android.Net.Uri file = Android.Support.V4.Content.FileProvider.GetUriForFile(MainActivity.mactivity, MainActivity.mactivity.PackageName + ".fileprovider", new Java.IO.File(path));
        Intent intent = new Intent(Intent.ActionView);
        intent.SetDataAndType(file, "application/pdf");
        intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask | ActivityFlags.GrantReadUriPermission | ActivityFlags.NewTask|ActivityFlags.NoHistory);
       
        try
        {
            MainActivity.mactivity.ApplicationContext.StartActivity(intent);              
        }
        catch (Exception)
        {
            Toast.MakeText(Xamarin.Forms.Forms.Context, "No Application Available to View PDF", ToastLength.Short).Show();
        }
    }
}
}

在共享代码项目中,在button.click中打开pdf

 private void btnopen_Clicked(object sender, EventArgs e)
    {
        DependencyService.Get<Iopenpdf>().openpdf();
    }

【讨论】:

  • 感谢您的回答,非常感谢。经过 3 天的研究和测试不同的解决方案,似乎更好的实现使用DependencyService 为每个解决方案进行具体实现。 IO、机器人、UWP。我担心在共享项目中使用特定的 Android 库。
  • @yensei 是的,我的回答也是使用DependencyService为各个平台打开pdf,关于DependencyService,请看我的更新。
  • 谢谢樱桃。我需要一些权限才能将我的文件写入 /storage/emulated/0/Download,当我尝试时我有 UnauthorizedAccessException
  • @yensei 是的,您需要在AndroidMainfeast.xml 中添加权限WRITE_EXTERNAL_STORAGEREAD_EXTERNAL_STORAGE,然后您还需要在Android 6.0 中进行运行时权限检查。我在回复中提到过。
  • 我在努力完成这项工作时学到了很多东西。现在我只需要打开 pdf,但是当我到达 openpdffile 的方法时,我有IllegalArgumentException,消息显示Failed to find configured root that contains /storage/emulated/0/Android/data/my.package/files/myfile.pdf。如果这是问题,我尝试使用不同的文件夹丢弃
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-21
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-01
  • 1970-01-01
相关资源
最近更新 更多