我尝试在iOS设备上打开现有的PDF文件。 必须使用默认的PDF阅读器打开此文件。
在这一刻,我使用"依赖服务"运行本机代码。
public void Save(string filename, byte[] byPDF)
{
string strPfad = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), filename);
if(File.Exists(strPfad))
{
File.Delete(strPfad);
File.WriteAllBytes(strPfad, byPDF);
}
else
File.WriteAllBytes(strPfad, byPDF);
var viewer = UIDocumentInteractionController.FromUrl(NSUrl.FromFilename(strPfad));
var controller = GetVisibleViewController();
viewer.PresentOpenInMenu(controller.View.Frame, controller.View, true);
}
private UIViewController GetVisibleViewController(UIViewController controller = null)
{
controller = controller ?? UIApplication.SharedApplication.KeyWindow.RootViewController;
if (controller.PresentedViewController == null)
return controller;
if (controller.PresentedViewController is UINavigationController)
{
return ((UINavigationController)controller.PresentedViewController).VisibleViewController;
}
if (controller.PresentedViewController is UITabBarController)
{
return ((UITabBarController)controller.PresentedViewController).SelectedViewController;
}
return GetVisibleViewController(controller.PresentedViewController);
}
如果我运行此代码,则不会发生任何事情(仅写入文件)。
答案 0 :(得分:2)
我刚使用标准的UIViewController并将路径(pdf保存在设备上)传递给控制器并将其加载到UIWebview中。
public class PdfController : UIViewController
{
public PdfController(string pdfPath)
{
NavigationItem.LeftBarButtonItem = new NavBarButton("Back", (sender, args) =>
{
NavigationController.PopViewController(true);
});
var webView = new UIWebView(View.Bounds);
View.AddSubview(webView);
webView.LoadRequest(new NSUrlRequest(new NSUrl(pdfPath, false)));
webView.ScalesPageToFit = true;
}
}
但您需要先下载它并将其传递给此控制器 这个snippit将允许您下载pdf并保存。
Public void DownloadPDF()
{
Utility.AddNetworkConnection();
var webClient = new WebClient();
loadingView = new LoadingView();
loadingView.Show("Downloading PDF");
webClient.DownloadDataCompleted += (s, e) =>
{
Utility.RemoveNetworkConnection();
File.WriteAllBytes(_pdfPathLocation, e.Result); // writes to local storage
InvokeOnMainThread(() =>
{
loadingView.Hide();
_pdfImageElement.SetValueAndUpdate("Open PDF");
var a = new UIAlertView("Done", "File downloaded and saved", null, "OK", "Open PDF");
a.Show();
a.Clicked += OpenPdf;
});
};
var url = new Uri(_wreck.PdfURL);
webClient.Encoding = Encoding.UTF8;
webClient.DownloadDataAsync(url);
}