我想在任何PDFviewer中打开PDF,并且我的pdf文件放置在资产文件夹中。
我尝试执行以下操作,但是File Provider自targetversion> 24起也发挥了作用。我还实现了FileProvider
文件中的Manifest
和资源下xml文件夹中的filepath文件。请帮忙。
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();
}
答案 0 :(得分:0)
这是我使用意图选择器执行上述操作的方式:
使用以下方法从资产文件夹中获取流:
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;
查询时还原
祝你好运!