Maui:在android上使用acrobat reader打开捆绑的(资产)pdf文件

ylamdve6  于 2023-05-05  发布在  Android
关注(0)|答案(1)|浏览(237)

我的应用程序在Resources\Raw\helpfile.pdf下有一个PDF帮助文件。在Android上,应该通过将其“发送”到Acrobat Reader来打开(前提是它安装在设备上)。
我尝试了一个类似“从捆绑文件写入应用程序数据文件夹”的编码,显示为here

string targetpath = System.IO.Path.Combine(FileSystem.Current.AppDataDirectory, "helpfile.pdf");
if (targetpath != null
    && File.Exists(targetpath))
{
    File.Delete(targetpath); // the help file could be newer
}

var stream = await FileSystem.Current.OpenAppPackageFileAsync("helpfile.pdf");
StreamReader reader = new StreamReader(stream);
var content = await reader.ReadToEndAsync();
reader.Close();

FileStream outputStream = System.IO.File.OpenWrite(targetpath);
StreamWriter streamWriter = new StreamWriter(outputStream);
await streamWriter.WriteAsync(content);
streamWriter.Close();

await Launcher.Default.OpenAsync(new OpenFileRequest("helpfile.pdf", new ReadOnlyFile(targetpath)));

在安装了Acrobat Reader的Android模拟器(API 33)上,Reader打开,但除了(正确数量的)页制动器之外,文件为空。
可能是var content = await reader.ReadToEndAsync()的问题,因为它提供了一个字符串,这并不代表正确的编码的pdf文件。
是否有其他方法将资源复制到可访问的路径?

oyxsuwqo

oyxsuwqo1#

使用BinaryWriter将pdf文件复制到Android AppDataDirectory

var filePath = Path.Combine(FileSystem.AppDataDirectory, $"important_copy.pdf");  

using (Stream inputStream = await FileSystem.OpenAppPackageFileAsync("important.pdf")) // read pdf stored as MauiAsset
using (BinaryReader reader = new BinaryReader(inputStream)) // read bytes from pdf file as stream
using (FileStream outputStream = File.Create(filePath)) // create destination pdf file
using (BinaryWriter writer = new BinaryWriter(outputStream)) // write output stream to destination pdf
{
    // Read bytes from input stream and write to output stream
    byte[] buffer = new byte[4096];
    int bytesRead;
    while ((bytesRead = reader.Read(buffer, 0, buffer.Length)) > 0)
    {
        writer.Write(buffer, 0, bytesRead);
    }
}

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

相关问题