private async void MyMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e) { // Clear any existing popups. _myMapView.DismissCallout(); try { // Perform identify on the KML layer and get the results. IdentifyLayerResult identifyResult = await _myMapView.IdentifyLayerAsync(_forecastLayer, e.Position, 2, false); // Return if there are no results that are KML placemarks. if (!identifyResult.GeoElements.OfType <KmlGeoElement>().Any()) { return; } // Get the first identified feature that is a KML placemark KmlNode firstIdentifiedPlacemark = identifyResult.GeoElements.OfType <KmlGeoElement>().First().KmlNode; // Show a preview with the HTML content. _webView.LoadHtmlString(new NSString(firstIdentifiedPlacemark.BalloonContent), new NSUrl("")); } catch (Exception ex) { new UIAlertView("Error", ex.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show(); } }
private async void _myMapView_GeoViewTapped(object sender, GeoViewInputEventArgs e) { try { // Perform the identify operation. IdentifyLayerResult myIdentifyResult = await _myMapView.IdentifyLayerAsync(_wmsLayer, e.Position, 20, false); // Return if there's nothing to show. if (myIdentifyResult.GeoElements.Count < 1) { return; } // Retrieve the identified feature, which is always a WmsFeature for WMS layers. WmsFeature identifiedFeature = (WmsFeature)myIdentifyResult.GeoElements[0]; // Retrieve the WmsFeature's HTML content. string htmlContent = identifiedFeature.Attributes["HTML"].ToString(); // Note that the service returns a boilerplate HTML result if there is no feature found. // This would be a good place to check if the result looks like it includes feature details. // Show a preview with the HTML content. _webView.LoadHtmlString(new NSString(htmlContent), new NSUrl("")); } catch (Exception ex) { new UIAlertView("Error", ex.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show(); } }
void SegmentValueChanged(object sender, EventArgs e) { if (_viewSegment.SelectedSegment == 0) { if (_previewView != null) { _previewView.RemoveFromSuperview(); _previewView.Dispose(); _previewView = null; } Add(TextView); TextView.BecomeFirstResponder(); } else { if (_previewView == null) { _previewView = new WKWebView(this.View.Bounds, new WKWebViewConfiguration()); } TextView.RemoveFromSuperview(); Add(_previewView); var markdownService = Mvx.Resolve <IMarkdownService>(); var markdownText = markdownService.Convert(Text); var model = new DescriptionModel(markdownText, (int)UIFont.PreferredSubheadline.PointSize); var view = new MarkdownView { Model = model }.GenerateString(); _previewView.LoadHtmlString(view, NSBundle.MainBundle.BundleUrl); } }
/// <summary> /// Produces PNG from HTML /// </summary> /// <param name="taskCompletionSource"></param> /// <param name="html"></param> /// <param name="fileName"></param> public void ToPng(TaskCompletionSource <ToFileResult> taskCompletionSource, string html, string fileName, int width) { if (NSProcessInfo.ProcessInfo.IsOperatingSystemAtLeastVersion(new NSOperatingSystemVersion(11, 0, 0))) { string jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"; WKUserScript wkUScript = new WKUserScript((NSString)jScript, WKUserScriptInjectionTime.AtDocumentEnd, true); WKUserContentController wkUController = new WKUserContentController(); wkUController.AddUserScript(wkUScript); var configuration = new WKWebViewConfiguration { UserContentController = wkUController }; var webView = new WKWebView(new CGRect(0, 0, width, width), configuration) { UserInteractionEnabled = false, BackgroundColor = UIColor.White }; webView.NavigationDelegate = new WKNavigationCompleteCallback(fileName, new WebViewToPngSize(width), null, taskCompletionSource, NavigationComplete); webView.LoadHtmlString(html, null); } else { taskCompletionSource.SetResult(new ToFileResult(true, "PNG output not available prior to iOS 11")); } }
public void AppDomainInitializer() { var userController = new WKUserContentController(); userController.AddScriptMessageHandler(this, "myapp"); var config = new WKWebViewConfiguration { UserContentController = userController }; webview_real = new WKWebView(View.Frame, config); View.AddSubview(webview_real); #region load from file string htmlPath = NSBundle.MainBundle.PathForResource("Alerts", "html"); string htmlContents = File.ReadAllText(htmlPath); webview_real.LoadHtmlString(htmlContents, null); #endregion #region load from url sample //var url = "https://www.google.com.tw"; //webview_real.LoadRequest(new NSUrlRequest(new NSUrl(url))); #endregion }
private void LoadWebView() { string path = Path.Combine(NSBundle.MainBundle.BundlePath, "HeatMap.html"); var contents = File.ReadAllText(path); var baseUrl = new NSUrl(NSBundle.MainBundle.BundlePath, true); _baseWebView.LoadHtmlString(contents, baseUrl); }
private void LoadHTML() { // Create the API key info section. string keyInfoPath = Path.Combine(NSBundle.MainBundle.BundlePath, "ApiKeyInfo.md"); string keyInfoContent = File.ReadAllText(keyInfoPath); string keyInfoHTML = HTMLHelpers.MarkdownToHTML(keyInfoContent, TraitCollection); _infoText.LoadHtmlString(keyInfoHTML, new NSUrl(_contentDirectoryPath, true)); }
public void DidFailNavigation(WKWebView webView, WKNavigation navigation, NSError error) { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; // Report the error inside the web view. var localizedErrorMessage = "An error occured:"; var errorHTML = string.Format("<!doctype html><html><body><div style=\"width: 100%%; text-align: center; font-size: 36pt;\">{0} {1}</div></body></html>", localizedErrorMessage, error.Description); webView.LoadHtmlString(errorHTML, null); }
private async Task LoadPreview(WKWebView previewView) { var markdownText = await _markdownService.Convert(Text); var model = new MarkdownModel(markdownText, (int)UIFont.PreferredSubheadline.PointSize); var view = new MarkdownWebView { Model = model }.GenerateString(); previewView.LoadHtmlString(view, NSBundle.MainBundle.BundleUrl); }
public override void ViewDidLoad () { base.ViewDidLoad (); // Create a new WKWebView, assign the delegate and add it to the view webView = new WKWebView(View.Frame, new WKWebViewConfiguration()); webView.UIDelegate = this; View.AddSubview (webView); // Find the Alerts.html file and load it into the WKWebView string htmlPath = NSBundle.MainBundle.PathForResource ("Alerts", "html"); string htmlContents = File.ReadAllText (htmlPath); webView.LoadHtmlString (htmlContents, null); }
public void ConvertHTMLtoPDF(PDFToHtml _PDFToHtml) { try { WKWebView webView = new WKWebView(new CGRect(0, 0, (int)_PDFToHtml.PageWidth, (int)_PDFToHtml.PageHeight), new WKWebViewConfiguration()); webView.UserInteractionEnabled = false; webView.BackgroundColor = UIColor.White; webView.NavigationDelegate = new WebViewCallBack(_PDFToHtml); webView.LoadHtmlString(_PDFToHtml.HTMLString, null); } catch { _PDFToHtml.Status = PDFEnum.Failed; } }
public override void ViewDidLoad() { base.ViewDidLoad(); // Create a new WKWebView, assign the delegate and add it to the view webView = new WKWebView(View.Frame, new WKWebViewConfiguration()); webView.UIDelegate = this; View.AddSubview(webView); // Find the Alerts.html file and load it into the WKWebView string htmlPath = NSBundle.MainBundle.PathForResource("Alerts", "html"); string htmlContents = File.ReadAllText(htmlPath); webView.LoadHtmlString(htmlContents, null); }
public async void CheckReloadWebView(CancellationToken token, WKWebView webView) { try { await Task.Delay(5000, token); webView.EvaluateJavaScript("document.body.getBoundingClientRect().bottom", completionHandler: (height, error) => { if (!IsDisappeared && (error != null || String.IsNullOrWhiteSpace(height.Description) || int.Parse(height.Description) < 4)) { Platform.ClearBrowserCache(); webView.LoadHtmlString(Challenge.Desc, null); } }); } catch (Exception) { } }
public Task <string> GetUserAgentAsync(CancellationToken cancellationToken) { if (!string.IsNullOrWhiteSpace(_userAgent)) { return(Task.FromResult(_userAgent)); } var taskCompletionSource = new TaskCompletionSource <string>(); this.InvokeOnMainThreadIfNeeded(async() => { try { using (var webView = new WKWebView(CGRect.Empty, new WKWebViewConfiguration())) { webView.LoadHtmlString("<html></html>", null); if (cancellationToken.IsCancellationRequested) { taskCompletionSource.TrySetCanceled(); return; } var userAgent = await webView .EvaluateJavaScriptAsync("navigator.userAgent") .ConfigureAwait(false); _userAgent = userAgent as NSString; taskCompletionSource.TrySetResult(_userAgent); } } catch (Exception exception) { taskCompletionSource.TrySetException(exception); } }); return(taskCompletionSource.Task); }
public string SafeHTMLToPDF(string html, string filename) { //WKWebView webView = new WKWebView(new CGRect(0, 0, 6.5 * 72, 9 * 72)); var config = new WKWebViewConfiguration(); WKWebView webView = new WKWebView(new CGRect(0, 0, 6.5 * 72, 9 * 72), config); var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var file = Path.Combine(documents, "Invoice" + "_" + DateTime.Now.ToShortDateString() + "_" + DateTime.Now.ToShortTimeString() + ".pdf"); webView.NavigationDelegate = new WebViewCallBack(file); //webView.Delegate = new WebViewCallBack(file); //webView.ScalesPageToFit = true; webView.UserInteractionEnabled = false; webView.BackgroundColor = UIColor.White; webView.LoadHtmlString(html, null); return(file); }
public override void ViewDidLoad() { base.ViewDidLoad(); // Perform any additional setup after loading the view, typically from a nib. wKWebView = new WKWebView(View.Frame, new WKWebViewConfiguration()); View.AddSubview(wKWebView); var bundle = NSBundle.MainBundle; var path = bundle.PathForResource("map", "html"); var html = string.Empty; try { html = File.ReadAllText(path, Encoding.UTF8); } catch { //ERROR } wKWebView.LoadHtmlString(html, null); wKWebView.AllowsBackForwardNavigationGestures = true; }
public void AddUrlOverride(string url, Func <string> action) { if (_webView == null) { throw new System.Exception("WebView and WebViewClient were not initialized"); } _webViewClient.AddOverrideUrl(url, action); var schemeHandler = new TrestleSchemeHandler(); schemeHandler.AddOverrideUrl(url, action); _configuration.SetUrlSchemeHandler(schemeHandler, "trestle"); _webView.EvaluateJavaScript("document.documentElement.outerHTML.toString()", (NSObject result, NSError err) => { if (err != null) { System.Console.WriteLine(err); } if (result != null) { _html = result.ToString(); } }); _webView.RemoveFromSuperview(); _webView = new WKWebView(_layout.Bounds, _configuration); _webView.TranslatesAutoresizingMaskIntoConstraints = false; _webView.NavigationDelegate = _webViewClient; _layout.AddSubview(_webView); NSLayoutConstraint.Create(_webView, NSLayoutAttribute.CenterX, NSLayoutRelation.Equal, _layout, NSLayoutAttribute.CenterX, 1f, 0f).Active = true; NSLayoutConstraint.Create(_webView, NSLayoutAttribute.CenterY, NSLayoutRelation.Equal, _layout, NSLayoutAttribute.CenterY, 1f, 0f).Active = true; _webView.SetNeedsDisplay(); _webView.LoadHtmlString(_html, null); }
public void ToPdf(TaskCompletionSource <ToFileResult> taskCompletionSource, string html, string fileName, PageSize pageSize, PageMargin margin) { if (NSProcessInfo.ProcessInfo.IsOperatingSystemAtLeastVersion(new NSOperatingSystemVersion(11, 0, 0))) { string jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);"; WKUserScript wkUScript = new WKUserScript((NSString)jScript, WKUserScriptInjectionTime.AtDocumentEnd, true); WKUserContentController wkUController = new WKUserContentController(); wkUController.AddUserScript(wkUScript); var configuration = new WKWebViewConfiguration { UserContentController = wkUController }; //webView = new WKWebView(new CGRect(0, 0, (size.Width - 0.5) * 72, (size.Height - 0.5) * 72), configuration) var webView = new WKWebView(new CGRect(0, 0, pageSize.Width, pageSize.Height), configuration) { UserInteractionEnabled = false, BackgroundColor = UIColor.White }; webView.NavigationDelegate = new WKNavigationCompleteCallback(fileName, pageSize, margin, taskCompletionSource, NavigationComplete); webView.LoadHtmlString(html, null); } }
public void LoadHtmlString(string html) { _html = html; _webView.LoadHtmlString(_html, null); }
public void LoadResource() { string htmlResource = _richTextEditor.LoadResources(); _webView.LoadHtmlString(htmlResource, new NSUrl(string.Empty)); }
private void Initialize() { CheckDarkMode(); // Build out readme html. try { string markdownFile = _darkMode ? _darkMarkdownFile : _lightMarkdownFile; string readmePath = Path.Combine(NSBundle.MainBundle.BundlePath, "Samples", _info.Category, _info.FormalName, "readme.md"); string readmeCSSPath = Path.Combine(NSBundle.MainBundle.BundlePath, $"SyntaxHighlighting/{markdownFile}"); string readmeContent = new MarkedNet.Marked().Parse(File.ReadAllText(readmePath)); string readmeHTML = "<!doctype html><head><base href=\"" + readmePath + "\"><link rel=\"stylesheet\" href=\"" + readmeCSSPath + "\" />" + "<meta name=\"viewport\" content=\"width=" + UIScreen.MainScreen.Bounds.Width.ToString() + ", shrink-to-fit=YES\">" + "</head>" + "<body class=\"markdown-body\">" + readmeContent + "</body>"; // Load the readme into the webview. _readmeView.LoadHtmlString(readmeHTML, new NSUrl(_contentDirectoryPath, true)); } catch (Exception ex) { Debug.WriteLine(ex.Message); _readmeView.LoadHtmlString("Could not load information.", new NSUrl(_contentDirectoryPath, true)); } // Build out source code html. try { string syntaxFile = _darkMode ? _darkSyntaxFile : _lightSyntaxFile; // Get the paths for the .css and .js files for syntax highlighting. string syntaxHighlightCSS = Path.Combine(NSBundle.MainBundle.BundlePath, $"SyntaxHighlighting/{syntaxFile}"); string jsPath = Path.Combine(NSBundle.MainBundle.BundlePath, "SyntaxHighlighting/highlight.pack.js"); // Start and end HTML tags. const string _sourceHTMLStart = "<html>" + "<head>" + "<link rel=\"stylesheet\" href=\"{csspath}\">" + "<script type=\"text/javascript\" src=\"{jspath}\"></script>" + "<script>hljs.initHighlightingOnLoad();</script>" + "</head>" + "<body>" + "<pre>"; const string _sourceHTMLEnd = "</pre>" + "</body>" + "</html>"; string sourceFilesPath = Path.Combine(NSBundle.MainBundle.BundlePath, "Samples", _info.Category, _info.FormalName); // Create a dictionary of the files. _sourceCodeFiles = new Dictionary <string, string>(); // Loop over every source code file in the sample directory. foreach (string sourceCodePath in Directory.GetFiles(sourceFilesPath, "*.cs")) { // Get the code as a string. string baseContent = File.ReadAllText(sourceCodePath); // Build the html. string sourceCodeHTML = _sourceHTMLStart.Replace("{csspath}", syntaxHighlightCSS).Replace("{jspath}", jsPath) + "<code class=\"csharp\">" + baseContent + "</code>" + _sourceHTMLEnd; // Get the filename without the full path. string shortPath = sourceCodePath.Split('/').Last(); // Add the html to the source code files dictionary. _sourceCodeFiles.Add(shortPath, sourceCodeHTML); } // Load the first source code file into the web view. string firstKey = _sourceCodeFiles.Keys.First(); _codeWebView.LoadHtmlString(_sourceCodeFiles[firstKey], new NSUrl(_contentDirectoryPath, true)); _codeButton.Title = firstKey; } catch (Exception ex) { Debug.WriteLine(ex.Message); _codeWebView.LoadHtmlString("Could not load source code.", new NSUrl(_contentDirectoryPath, true)); _codeButton.Enabled = false; } }