如何以 xamarin 形式打开 PDF 文件 [英] How to open PDF file in xamarin forms
问题描述
我将 PDF 文件下载为 byte[] 并使用 File.WriteAllBytes(path, response);
将其保存到内部存储中.
I downloaded a PDF file as byte[] and save it into internal storage using File.WriteAllBytes(path, response);
.
现在无法从 android 模拟器访问它,我如何将它保存在下载文件夹中?我需要什么才能从安装在模拟器中的 pdf 阅读器打开它?
Now cannot access to it from android emulator, how could I save it on download folder? And what I need to be able to open it from pdf reader installed into emulator?
推荐答案
如何将其保存在下载文件夹中?
how could I save it on download folder?
对于android,您可以将pdf文件保存在下载文件夹 按照以下路径.
For android, you can save pdf file in download folder by following path.
string rootPath = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
对于ios,使用这个目录 存储用户文档和应用程序数据文件.
For ios, use this directory to store user documents and application data files.
var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments);
关于在Anaroid中打开pdf,可以使用如下代码:
About open pdf in Anaroid, you can use the following code:
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.
you need to add permission WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE in AndroidMainfeast.xml, then you also need to Runtime Permission Checks in Android 6.0.
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 文件中添加一个提供程序:
Also add a provider in the AndroidManifest.xml file:
<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中添加外部路径
And add an external path in Resources/xml/file_paths.xml
<external-path name="external_files" path="."/>
MainActivity.mactivity
是 MainActivity.cs 中的静态属性:
MainActivity.mactivity
is static property in 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,可以看一下:
About open pdf in ios, you can take a look:
更新:
我的回答也是使用 DependencyService,您可以在共享项目中创建 iterface.
My answer is also using DependencyService, you can create iterface in shared project.
public interface Iopenpdf
{
void openpdf();
}
在Android平台上,实现这个接口.
In Android platform, implement this interface.
[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
In shared code project, open pdf in button.click
private void btnopen_Clicked(object sender, EventArgs e)
{
DependencyService.Get<Iopenpdf>().openpdf();
}
这篇关于如何以 xamarin 形式打开 PDF 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!