有没有办法在不使用自定义渲染器的情况下使用xamarin表单查看PDF文件。
答案 0 :(得分:7)
机器人:
public void OpenPdf(string filePath)
{
Android.Net.Uri uri = Android.Net.Uri.Parse("file:///" + filePath);
Intent intent = new Intent(Intent.ActionView);
intent.SetDataAndType(uri, "application/pdf");
intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
try
{
Xamarin.Forms.Forms.Context.StartActivity(intent);
}
catch (Exception)
{
Toast.MakeText(Xamarin.Forms.Forms.Context, "No Application Available to View PDF", ToastLength.Short).Show();
}
}
iOS,有点复杂并且需要一些额外的课程:
public void OpenPDF(string filePath)
{
FileInfo fi = new FileInfo(filePath);
QLPreviewController previewController = new QLPreviewController();
previewController.DataSource = new PDFPreviewControllerDataSource(fi.FullName, fi.Name);
UINavigationController controller = FindNavigationController();
if (controller != null)
controller.PresentViewController(previewController, true, null);
}
private UINavigationController FindNavigationController()
{
foreach (var window in UIApplication.SharedApplication.Windows)
{
if (window.RootViewController.NavigationController != null)
return window.RootViewController.NavigationController;
else
{
UINavigationController val = CheckSubs(window.RootViewController.ChildViewControllers);
if (val != null)
return val;
}
}
return null;
}
private UINavigationController CheckSubs(UIViewController[] controllers)
{
foreach (var controller in controllers)
{
if (controller.NavigationController != null)
return controller.NavigationController;
else
{
UINavigationController val = CheckSubs(controller.ChildViewControllers);
if (val != null)
return val;
}
}
return null;
}
public class PDFItem : QLPreviewItem
{
string title;
string uri;
public PDFItem(string title, string uri)
{
this.title = title;
this.uri = uri;
}
public override string ItemTitle
{
get { return title; }
}
public override NSUrl ItemUrl
{
get { return NSUrl.FromFilename(uri); }
}
}
public class PDFPreviewControllerDataSource : QLPreviewControllerDataSource
{
string url = "";
string filename = "";
public PDFPreviewControllerDataSource(string url, string filename)
{
this.url = url;
this.filename = filename;
}
public override QLPreviewItem GetPreviewItem(QLPreviewController controller, int index)
{
return new PDFItem(filename, url);
}
public override int PreviewItemCount(QLPreviewController controller)
{
return 1;
}
}
使用依赖服务来获取它们并根据需要调用,对我来说效果很好。 PDFItem和PDFPreviewControllerDataSource类来自一个博客,我不能为我的生活记住它的名字,但它们不是我的工作。在您的情况下可能不需要FindNavigationController,它可能很简单:
UISharedApplication.KeyWindow.PresentViewController
您可以在此处找到相关信息: https://forums.xamarin.com/discussion/25746/how-to-open-pdf-in-xamarin-forms
答案 1 :(得分:4)
现在有一个包含这个问题的方法:https://developer.xamarin.com/recipes/cross-platform/xamarin-forms/controls/display-pdf/
编辑:哎呀,配方确实使用自定义渲染器。如果你不能在没有自定义渲染器的情况下使它工作,它可能仍然有用。