我想在任何PDFviewer中打开PDF,我的pdf文件放在assets文件夹中。
我试过做以下但文件提供程序也扮演一个部分,因为targetversion> 24。我还在FileProvider
文件中实现了Manifest
,在资源下的xml文件夹中实现了一个文件路径文件。请帮忙。
string fileName = "myProfile.pdf";
var localFolder = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var MyFilePath = System.IO.Path.Combine(localFolder, fileName);
using (var streamReader = new StreamReader(_activity.Assets.Open(fileName)))
{
using (var memstream = new MemoryStream())
{
streamReader.BaseStream.CopyTo(memstream);
var bytes = memstream.ToArray();
//write to local storage
System.IO.File.WriteAllBytes(MyFilePath, bytes);
MyFilePath = $"file://{localFolder}/{fileName}";
}
}
var fileUri = Android.Net.Uri.Parse(MyFilePath);
Intent intent = new Intent(Intent.ActionView);
intent.SetDataAndType(fileUri, "application/pdf");
intent.SetFlags(ActivityFlags.ClearTop);
intent.SetFlags(ActivityFlags.NewTask);
try
{
_activity.StartActivity(intent);
}
catch (ActivityNotFoundException ex)
{
Toast.MakeText(_activity, "NO Pdf Viewer", ToastLength.Short).Show();
}
这就是我使用意图选择器来执行上述操作的方法:
使用以下内容从assets文件夹中获取流:
public Stream GetFromAssets(Context context, string assetName)
{
AssetManager assetManager = context.Assets;
Stream inputStream;
try
{
using (inputStream = assetManager.Open(assetName))
{
return inputStream;
}
}
catch (Exception e)
{
return null;
}
}
为byte []转换添加以下辅助方法:
public byte[] ReadFully(Stream input)
{
using (MemoryStream ms = new MemoryStream())
{
input.CopyTo(ms);
return ms.ToArray();
}
然后按如下所示更新Open pdf方法,它应该工作:
private void OpenPDF(Stream inputStream)
{
var bytearray = ReadFully(inputStream);
Java.IO.File file = (Java.IO.File)Java.IO.File.FromArray(bytearray);
var target = new Intent(Intent.ActionView);
target.SetDataAndType(Android.Net.Uri.FromFile(file), "application/pdf");
target.SetFlags(ActivityFlags.NoHistory);
Intent intent = Intent.CreateChooser(target, "Open File");
try
{
this.StartActivity(intent);
}
catch (ActivityNotFoundException ex)
{
// Instruct the user to install a PDF reader here, or something
}
}
我通过我的pdf文件的字符串路径来提出Java.IO.File
基本上,添加以下using语句:
using Java.IO;
using Android.Content;
using Android.Net;
在查询时还原
祝好运!