[英]How do I display a pdf file in Xamarin.Android?
I have converted and saved a base64 string to a pdf file.我已将 base64 字符串转换并保存到 pdf 文件中。 Currently, I have the following code to open the PDF:
目前,我有以下代码来打开 PDF:
public void Pdf(string blob)
{
try
{
string filePath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "agremeent.pdf");
try
{
if (blob != null)
{
Java.IO.File file = new Java.IO.File(filePath);
if (!file.Exists())
{
file.Delete();
}
fos = new FileOutputStream(filePath);
var bytes = Base64.Decode(blob, Base64Flags.Default);
fos.Write(bytes);
fos.Flush();
fos.Close();
}
}
catch (Exception e)
{
}
finally
{
if (fos != null)
{
fos = null;
}
}
Android.Net.Uri url = Android.Net.Uri.Parse(filePath);
Intent target = new Intent(Intent.ActionView);
target.SetDataAndType(url, "application/pdf");
Intent intent = Intent.CreateChooser(target, "Open File");
try
{
StartActivity(intent);
}
catch (ActivityNotFoundException e)
{
// Instruct the user to install a PDF reader here, or something
}
}
catch
{
}
}
This lets user choose which PDF viewer they would like to use to open the PDF.这让用户可以选择他们想使用哪个 PDF 查看器来打开 PDF。 But, the PDF isn't opening in Google Drive.
但是,PDF 没有在 Google Drive 中打开。 What is causing this?
这是什么原因造成的? Is there a way to open the PDF without leaving the app and using a third party viewer?
有没有办法在不离开应用程序并使用第三方查看器的情况下打开 PDF?
Answer: You can use the Xamarin.Bindings.PDFView-Android package and create an activity to show the pdf.答:您可以使用 Xamarin.Bindings.PDFView-Android package 并创建一个活动来显示 pdf。 It can make Android display the pdf easily.
它可以使Android轻松显示pdf。 Such as: MainActicity.xml:
如:MainActicity.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.pdfview.PDFView
android:id="@+id/pdfview"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</LinearLayout>
MainActivity.cs: MainActivity.cs:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
string filePath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "agremeent.pdf");
var pdfview = this.FindViewById<PDFView>(Resource.Id.pdfview);
Java.IO.File file = new Java.IO.File(filePath);
pdfview.FromFile(file).Show();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.