Пример #1
0
        public override bool PrintDocumentFromWebView(object webView)
        {
            try {
                UIWebView platformWebView = (UIWebView)(webView as CustomWebView).PlatformControl;

                UIPrintInteractionController printer = UIPrintInteractionController.SharedPrintController;

                printer.ShowsPageRange = true;

                printer.PrintInfo            = UIPrintInfo.PrintInfo;
                printer.PrintInfo.OutputType = UIPrintInfoOutputType.General;
                printer.PrintInfo.JobName    = "BodyReportJob";

                printer.PrintPageRenderer = new UIPrintPageRenderer()
                {
                    HeaderHeight = 40,
                    FooterHeight = 40
                };
                printer.PrintPageRenderer.AddPrintFormatter(platformWebView.ViewPrintFormatter, 0);

                if (Device.Idiom == TargetIdiom.Phone)
                {
                    printer.PresentAsync(true);
                }
                else if (Device.Idiom == TargetIdiom.Tablet)
                {
                    printer.PresentFromRectInViewAsync(new CGRect(200, 200, 0, 0), platformWebView, true);
                }

                return(true);
            } catch (Exception) {
                return(false);
            }
        }
Пример #2
0
        /// <summary>
        /// Callback method that is called when printing completes (successfully or as a result of failure).
        /// </summary>
        /// <param name="_">The Print Interaction controller</param>
        /// <param name="completed">Flag indicating if printing has completed.</param>
        /// <param name="nsError">NSError value used to report errors during printing. Null if no error.</param>
        private static async void PrintCompletion(
            UIPrintInteractionController _,
            bool completed,
            NSError nsError)
        {
            try
            {
                if (completed)
                {
                    await PrintStatusReporting.ReportInfoAsync(
                        CrossPrinting.PrintingMessages.PrintInteractionCompleted);
                }
                else if (!completed && nsError != null)
                {
                    await PrintStatusReporting.ReportInfoAsync(
                        CrossPrinting.PrintingMessages.PrintInteractionError);
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
            {
                await PrintStatusReporting.ReportExceptionAsync(ex);
            }
#pragma warning restore CA1031 // Do not catch general exception types
        }
Пример #3
0
		void PrintingComplete (UIPrintInteractionController printInteractionController, bool completed, NSError error)
		{
			if (completed && error != null) {
				string message = String.Format ("Due to error in domain `{0}` with code: {1}", error.Domain, error.Code);
				Console.WriteLine ("FAILED! {0}", message);
				new UIAlertView ("Failed!", message, null, "OK", null).Show ();
			}
		}
 void PrintingComplete(UIPrintInteractionController printInteractionController, bool completed, NSError error)
 {
     if (completed && error != null)
     {
         string message = String.Format("Due to error in domain `{0}` with code: {1}", error.Domain, error.Code);
         Console.WriteLine("FAILED! {0}", message);
         new UIAlertView("Failed!", message, null, "OK", null).Show();
     }
 }
Пример #5
0
        public void Print(PSPDFPrintBarButtonItem barButton)
        {
            try
            {
                if (UIPrintInteractionController.PrintingAvailable)
                {
                    UIPrintInteractionController pic = UIPrintInteractionController.SharedPrintController;
                    if (pic != null)
                    {
                        // PrintInfo
                        UIPrintInfo printInfo = UIPrintInfo.PrintInfo;
                        printInfo.OutputType = UIPrintInfoOutputType.General;
                        printInfo.JobName    = "Print Job: eBriefing";
                        printInfo.Duplex     = UIPrintInfoDuplex.None;

                        if (Orientation == ORIENTATION.LANDSCAPE)
                        {
                            printInfo.Orientation = UIPrintInfoOrientation.Landscape;
                        }
                        else
                        {
                            printInfo.Orientation = UIPrintInfoOrientation.Portrait;
                        }

                        pic.PrintInfo           = printInfo;
                        pic.ShowsNumberOfCopies = true;
                        pic.ShowsPaperSelectionForLoadedPapers = true;
                        pic.ShowsPageRange = false;

                        pic.PrintPageRenderer = renderer;

                        // Show print options
                        pic.PresentFromBarButtonItem(barButton, true, (printController, completed, error) =>
                        {
                            if (!completed && error != null)
                            {
                                Console.WriteLine("PrintHelper - Print Error Code " + error.Code);
                            }

                            renderer.Dispose();
                            renderer = null;
                            dict.Clear();
                            dict = null;
                        });
                    }
                }
                else
                {
                    new UIAlertView(StringRef.alert, "Print is not available at this time.", null, StringRef.ok, null).Show();
                }
            }
            catch (Exception ex)
            {
                Logger.WriteLineDebugging("PrintHelper - Print: {0}", ex.ToString());
            }
        }
        private void OnPrintingComplete(UIPrintInteractionController controller, bool completed, NSError error)
        {
            if (completed && error != null)
            {
                var message = $"Due to error in domain `{error.Domain}` with code: {error.Code}";
                Console.WriteLine($"FAILED! {message}");

                var alert = UIAlertController.Create("Failed!", message, UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                ShowViewController(alert, this);
            }
        }
Пример #7
0
        private static async Task <UIPrintInteractionController> PopulateCommonPrinterDetailsAsync(
            PrintJobConfiguration printJobConfiguration)
        {
            UIPrintInteractionController printer = UIPrintInteractionController.SharedPrintController;

            if (printer is null)
            {
                await PrintStatusReporting.ReportErrorAsync(
                    CrossPrinting.PrintingMessages.UnableToPrintAtThisTime);
            }
            else
            {
                printer.PrintInfo = UIPrintInfo.PrintInfo;

                if (!(printer.PrintInfo is null))
                {
                    if (!(printJobConfiguration is null))
                    {
                        switch (printJobConfiguration.DuplexPreference)
                        {
                        case PrintJobDuplexConfiguration.LongEdge:
                            printer.PrintInfo.Duplex = UIPrintInfoDuplex.LongEdge;
                            break;

                        case PrintJobDuplexConfiguration.ShortEdge:
                            printer.PrintInfo.Duplex = UIPrintInfoDuplex.ShortEdge;
                            break;

                        case PrintJobDuplexConfiguration.None:
                        default:
                            printer.PrintInfo.Duplex = UIPrintInfoDuplex.None;
                            break;
                        }

                        printer.PrintInfo.JobName = printJobConfiguration.JobName;

                        printer.PrintInfo.Orientation
                            = printJobConfiguration.PreferPortraitOrientation
                            ? UIPrintInfoOrientation.Portrait
                            : UIPrintInfoOrientation.Landscape;

                        printer.PrintInfo.OutputType
                            = printJobConfiguration.PreferColor
                            ? UIPrintInfoOutputType.General
                            : UIPrintInfoOutputType.Grayscale;
                    }
                }
                printer.ShowsPageRange = true;
            }

            return(printer);
        }
Пример #8
0
 private static void FinishPrinting(UIPrintInteractionController controller, bool completed, NSError error)
 {
     if (completed && error == null)
     {
         new UIAlertView(TouchFactory.Instance.GetResourceString("PrintingTitle"),
                         TouchFactory.Instance.GetResourceString("Printing"), null,
                         TouchFactory.Instance.GetResourceString("Dismiss"), null).Show();
     }
     else if (error != null)
     {
         new UIAlertView(TouchFactory.Instance.GetResourceString("Error"), error.LocalizedDescription,
                         null, TouchFactory.Instance.GetResourceString("Dismiss"), null).Show();
     }
 }
Пример #9
0
        private static async Task <bool> PrintObjectAsync(NSObject nsObject, PrintJobConfiguration printJobConfiguration)
        {
            bool result = false;

            UIPrintInteractionController printer = await PopulateCommonPrinterDetailsAsync(printJobConfiguration);

            if (!(printer is null))
            {
                printer.PrintingItem = nsObject;
                printer.Present(true, PrintCompletion);
                printer.Dispose();
                result = true;
            }

            return(result);
        }
 public UIPrinterCutterBehavior ChooseCutterBehavior(UIPrintInteractionController printInteractionController, NSNumber[] availableBehaviors)
 {
     // What does this printer support?
     foreach (var whatsAvailable in availableBehaviors)
     {
         var nameofEnum = Enum.GetName(typeof(UIPrinterCutterBehavior), whatsAvailable.Int16Value);
         Console.WriteLine($"AvailableBehavior : {nameofEnum}");
     }
     // If the printer supports CutAfterEachJob, use it, otherwise use the whatever the printer default is.
     if (availableBehaviors.Contains((int)UIPrinterCutterBehavior.CutAfterEachJob))
     {
         return(UIPrinterCutterBehavior.CutAfterEachJob);
     }
     else
     {
         return(UIPrinterCutterBehavior.PrinterDefault);
     }
 }
Пример #11
0
        private void _loadFinished(object sender, EventArgs e)
        {
            var webview = sender as UIWebView;
            UIPrintInteractionController controller = UIPrintInteractionController.SharedPrintController;

            if (null == controller)
            {
                return;
            }

            // 设置打印机的一些默认信息
            UIPrintInfo printInfo = UIPrintInfo.PrintInfo;

            // 输出类型
            printInfo.OutputType = UIPrintInfoOutputType.General;
            // 打印队列名称
            printInfo.JobName = "HtmlDemo";
            // 是否单双面打印
            printInfo.Duplex = UIPrintInfoDuplex.LongEdge;
            // 设置默认打印信息
            controller.PrintInfo = printInfo;

            // 显示页码范围
            controller.ShowsPageRange = true;

            // 预览设置
            UIPrintPageRenderer myRenderer = new UIPrintPageRenderer();

            // To draw the content of each page, a UIViewPrintFormatter is used.
            // 生成html格式
            UIViewPrintFormatter viewFormatter = webview.ViewPrintFormatter;

            myRenderer.AddPrintFormatter(viewFormatter, 0);
            // 渲染html
            controller.PrintPageRenderer = myRenderer;

            controller.Present(true, (handler, completed, err) =>
            {
                if (!completed && err != null)
                {
                    System.Diagnostics.Debug.WriteLine("Printer Error");
                }
            });
        }
Пример #12
0
        private static bool PrintUrl(string url)
        {
            if (!string.IsNullOrEmpty(url))
            {
                NSUrl item = new NSUrl(url);
                if (UIPrintInteractionController.CanPrint(item))
                {
                    UIPrintInfo printInfo = UIPrintInfo.PrintInfo;
                    printInfo.JobName = url.Substring(url.LastIndexOf(Path.DirectorySeparatorChar) + 1);

                    UIPrintInteractionController.SharedPrintController.PrintInfo    = printInfo;
                    UIPrintInteractionController.SharedPrintController.PrintingItem = item;

                    return(true);
                }
            }

            return(false);
        }
        void PrintSelectedRecipes(object sender, EventArgs args)
        {
            // Get a reference to the singleton iOS printing concierge
            UIPrintInteractionController printController = UIPrintInteractionController.SharedPrintController;

            // Instruct the printing concierge to use our custom UIPrintPageRenderer subclass when printing this job
            printController.PrintPageRenderer = new RecipePrintPageRenderer(recipes.Recipes);

            // Ask for a print job object and configure its settings to tailor the print request
            UIPrintInfo info = UIPrintInfo.PrintInfo;

            // B&W or color, normal quality output for mixed text, graphics, and images
            info.OutputType = UIPrintInfoOutputType.General;

            // Select the job named this in the printer queue to cancel our print request.
            info.JobName = "Recipes";

            // Instruct the printing concierge to use our custom print job settings.
            printController.PrintInfo = info;

            // Present the standard iOS Print Panel that allows you to pick the target Printer, number of pages, double-sided, etc.
            printController.Present(true, PrintingCompleted);
        }
Пример #14
0
        private async Task <bool> PrintUIViewAsync(UIView uiView, PrintJobConfiguration printJobConfiguration)
        {
            bool result = false;

            UIPrintInteractionController printer = await PopulateCommonPrinterDetailsAsync(printJobConfiguration);

            if (!(printer is null))
            {
                printer.PrintPageRenderer = new UIPrintPageRenderer()
                {
                    HeaderHeight = 40,
                    FooterHeight = 40
                };
                printer.PrintPageRenderer.AddPrintFormatter(uiView.ViewPrintFormatter, 0);

                UIPrintInteractionResult interactionResult;

                if (Device.Idiom == TargetIdiom.Tablet) // TODO - move to ApplicationType
                {
                    interactionResult =
                        await printer.PresentFromRectInViewAsync(new CGRect(200, 200, 0, 0), uiView, true);
                }
                else
                {
                    interactionResult = await printer.PresentAsync(true);
                }

                PrintCompletion(
                    interactionResult.PrintInteractionController,
                    interactionResult.Completed,
                    null);
                result = interactionResult.Completed;
                printer.Dispose();
            }

            return(result);
        }
Пример #15
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            UIInterfaceOrientation orientation = UIApplication.SharedApplication.StatusBarOrientation;
            float width = (float)View.Frame.Width;

            float height = (float)View.Frame.Height;

            if (orientation == UIInterfaceOrientation.LandscapeLeft || orientation == UIInterfaceOrientation.LandscapeRight)
            {
                width  = (float)View.Frame.Height;
                height = (float)View.Frame.Width;
            }

            WritePadAPI.setRecoFlag(WritePadAPI.recoGetFlags(), true, WritePadAPI.FLAG_USERDICT);
            WritePadAPI.setRecoFlag(WritePadAPI.recoGetFlags(), true, WritePadAPI.FLAG_ANALYZER);
            WritePadAPI.setRecoFlag(WritePadAPI.recoGetFlags(), true, WritePadAPI.FLAG_CORRECTOR);

            inkView                  = new InkView();
            inkView.Frame            = new CGRect(button_gap, header_height + button_gap, width - button_gap * 2, height);
            inkView.ContentMode      = UIViewContentMode.Redraw;
            inkView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
            View.Add(inkView);

            formattedText           = new UITextView();
            formattedText.Frame     = new CGRect(0, UIScreen.MainScreen.Bounds.Height * 0.02, UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Height);
            formattedText.TextColor = UIColor.Black;
            formattedText.Font      = UIFont.FromName("Baskerville", 28f);
            formattedText.Hidden    = true;
            View.Add(formattedText);

            inkView.OnReturnGesture += () => recognized_text = inkView.Recognize(true);
            inkView.OnReturnGesture += () => inkView.cleanView(true);
            inkView.OnCutGesture    += () => inkView.cleanView(true);
            inkView.OnUndoGesture   += () => inkView.cleanView(true);

            float x = (width - (button_width * 5 + button_gap * 5)) / 2;

            switchViewButton       = new UIButton(UIButtonType.Custom);
            switchViewButton.Frame = new CGRect(x, height - bottom_gap, button_width, button_height);
            switchViewButton.SetTitle("Switch View", UIControlState.Normal);
            switchViewButton.Font = UIFont.SystemFontOfSize(button_font_size);
            switchViewButton.SetTitleColor(UIColor.Blue, UIControlState.Normal);
            switchViewButton.SetTitleColor(UIColor.White, UIControlState.Highlighted);
            switchViewButton.AutoresizingMask = UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin;
            switchViewButton.TouchUpInside   += (object sender, EventArgs e) => {
                if (inkView.getNumPaths() > 0)
                {
                    recognized_text = inkView.Recognize(false);
                }
                if (!displayingFormatted && recognized_text != "" && recognized_text != "*Error*")
                {
                    formattedText.Text   = recognized_text;
                    formattedText.Text   = FormatLatex(recognized_text);
                    formattedText.Hidden = false;
                    inkView.Hidden       = true;
                    displayingFormatted  = true;
                    printButton.SetTitle("Print", UIControlState.Normal);
                }
                else if (displayingFormatted)
                {
                    formattedText.Hidden = true;
                    inkView.Hidden       = false;
                    displayingFormatted  = false;
                    printButton.SetTitle("Save", UIControlState.Normal);
                }
            };
            View.Add(switchViewButton);
            x                += (button_gap + button_width);
            clearButton       = new UIButton(UIButtonType.Custom);
            clearButton.Frame = new CGRect(x, height - bottom_gap, button_width, button_height);
            clearButton.SetTitle("Clear", UIControlState.Normal);
            clearButton.Font = UIFont.SystemFontOfSize(button_font_size);
            clearButton.SetTitleColor(UIColor.Blue, UIControlState.Normal);
            clearButton.SetTitleColor(UIColor.White, UIControlState.Highlighted);
            clearButton.AutoresizingMask = UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin;
            clearButton.TouchUpInside   += (object sender, EventArgs e) => {
                inkView.cleanView(true);
            };
            View.Add(clearButton);

            x += (button_gap + button_width);
            languageButton       = new UIButton(UIButtonType.Custom);
            languageButton.Frame = new CGRect(x, height - bottom_gap, button_width, button_height);
            languageButton.SetTitle("Language", UIControlState.Normal);
            languageButton.Font = UIFont.SystemFontOfSize(button_font_size);
            languageButton.SetTitleColor(UIColor.Blue, UIControlState.Normal);
            languageButton.SetTitleColor(UIColor.White, UIControlState.Highlighted);
            languageButton.AutoresizingMask = UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin;
            languageButton.TouchUpInside   += (object sender, EventArgs e) => {
                var actionSheet = new UIActionSheet("Select Language:", (IUIActionSheetDelegate)null, "Cancel", null,
                                                    new [] { "English", "English UK", "German", "French", "Spanish", "Portuguese", "Brazilian", "Dutch", "Italian", "Finnish", "Swedish", "Norwegian", "Danish", "Indonesian" });
                actionSheet.Clicked += delegate(object a, UIButtonEventArgs b) {
                    switch (b.ButtonIndex)
                    {
                    case 0:
                        WritePadAPI.language = WritePadAPI.LanguageType.en;
                        from_language        = "en";
                        break;

                    case 1:
                        WritePadAPI.language = WritePadAPI.LanguageType.en_uk;
                        from_language        = "en";
                        break;

                    case 2:
                        WritePadAPI.language = WritePadAPI.LanguageType.de;
                        from_language        = "de";
                        break;

                    case 3:
                        WritePadAPI.language = WritePadAPI.LanguageType.fr;
                        from_language        = "fr";
                        break;

                    case 4:
                        WritePadAPI.language = WritePadAPI.LanguageType.es;
                        from_language        = "es";
                        break;

                    case 5:
                        WritePadAPI.language = WritePadAPI.LanguageType.pt_PT;
                        from_language        = "pt";
                        break;

                    case 6:
                        WritePadAPI.language = WritePadAPI.LanguageType.pt_BR;
                        from_language        = "pt";
                        break;

                    case 7:
                        WritePadAPI.language = WritePadAPI.LanguageType.nl;
                        from_language        = "nl";
                        break;

                    case 8:
                        WritePadAPI.language = WritePadAPI.LanguageType.it;
                        from_language        = "it";
                        break;

                    case 9:
                        WritePadAPI.language = WritePadAPI.LanguageType.fi;
                        from_language        = "fi";
                        break;

                    case 10:
                        WritePadAPI.language = WritePadAPI.LanguageType.sv;
                        from_language        = "sv";
                        break;

                    case 11:
                        WritePadAPI.language = WritePadAPI.LanguageType.nb;
                        from_language        = "nb";
                        break;

                    case 12:
                        WritePadAPI.language = WritePadAPI.LanguageType.da;
                        from_language        = "da";
                        break;

                    case 13:
                        WritePadAPI.language = WritePadAPI.LanguageType.id;
                        from_language        = "id";
                        break;
                    }
                    WritePadAPI.recoFree();
                    WritePadAPI.recoInit();
                    WritePadAPI.initializeFlags();
                };
                actionSheet.ShowInView(View);
            };
            View.Add(languageButton);

            x += (button_gap + button_width);
            translateButton       = new UIButton(UIButtonType.Custom);
            translateButton.Frame = new CGRect(x, height - bottom_gap, button_width, button_height);
            translateButton.SetTitle("Translate", UIControlState.Normal);
            translateButton.Font = UIFont.SystemFontOfSize(button_font_size);
            translateButton.SetTitleColor(UIColor.Blue, UIControlState.Normal);
            translateButton.SetTitleColor(UIColor.White, UIControlState.Highlighted);
            translateButton.AutoresizingMask = UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin;
            translateButton.TouchUpInside   += (object sender, EventArgs e) => {
                var translateActionSheet = new UIActionSheet("Select Language:", (IUIActionSheetDelegate)null, "Cancel", null,
                                                             new [] { "English", "English UK", "German", "French", "Spanish", "Portuguese", "Brazilian", "Dutch", "Italian", "Finnish", "Swedish", "Norwegian", "Danish", "Indonesian" });
                translateActionSheet.Clicked += delegate(object a, UIButtonEventArgs b) {
                    switch (b.ButtonIndex)
                    {
                    case 0:
                        to_language     = "en";
                        recognized_text = inkView.Recognize(false);
                        if (!displayingFormatted && recognized_text != "" && recognized_text != "*Error*")
                        {
                            Translate(FormatLatex(recognized_text));
                        }
                        break;

                    case 1:
                        to_language     = "en";
                        recognized_text = inkView.Recognize(false);
                        if (!displayingFormatted && recognized_text != "" && recognized_text != "*Error*")
                        {
                            Translate(FormatLatex(recognized_text));
                        }
                        break;

                    case 2:
                        to_language     = "de";
                        recognized_text = inkView.Recognize(false);
                        if (!displayingFormatted && recognized_text != "" && recognized_text != "*Error*")
                        {
                            Translate(FormatLatex(recognized_text));
                        }
                        break;

                    case 3:
                        to_language     = "fr";
                        recognized_text = inkView.Recognize(false);
                        if (!displayingFormatted && recognized_text != "" && recognized_text != "*Error*")
                        {
                            Translate(FormatLatex(recognized_text));
                        }
                        break;

                    case 4:
                        to_language     = "es";
                        recognized_text = inkView.Recognize(false);
                        if (!displayingFormatted && recognized_text != "" && recognized_text != "*Error*")
                        {
                            Translate(FormatLatex(recognized_text));
                        }
                        break;

                    case 5:
                        to_language     = "pt";
                        recognized_text = inkView.Recognize(false);
                        if (!displayingFormatted && recognized_text != "" && recognized_text != "*Error*")
                        {
                            Translate(FormatLatex(recognized_text));
                        }
                        break;

                    case 6:
                        to_language     = "pt";
                        recognized_text = inkView.Recognize(false);
                        if (!displayingFormatted && recognized_text != "" && recognized_text != "*Error*")
                        {
                            Translate(FormatLatex(recognized_text));
                        }
                        break;

                    case 7:
                        to_language     = "nl";
                        recognized_text = inkView.Recognize(false);
                        if (!displayingFormatted && recognized_text != "" && recognized_text != "*Error*")
                        {
                            Translate(FormatLatex(recognized_text));
                        }
                        break;

                    case 8:
                        to_language     = "it";
                        recognized_text = inkView.Recognize(false);
                        if (!displayingFormatted && recognized_text != "" && recognized_text != "*Error*")
                        {
                            Translate(FormatLatex(recognized_text));
                        }
                        break;

                    case 9:
                        to_language     = "fi";
                        recognized_text = inkView.Recognize(false);
                        if (!displayingFormatted && recognized_text != "" && recognized_text != "*Error*")
                        {
                            Translate(FormatLatex(recognized_text));
                        }
                        break;

                    case 10:
                        to_language     = "sv";
                        recognized_text = inkView.Recognize(false);
                        if (!displayingFormatted && recognized_text != "" && recognized_text != "*Error*")
                        {
                            Translate(FormatLatex(recognized_text));
                        }
                        break;

                    case 11:
                        to_language     = "nb";
                        recognized_text = inkView.Recognize(false);
                        if (!displayingFormatted && recognized_text != "" && recognized_text != "*Error*")
                        {
                            Translate(FormatLatex(recognized_text));
                        }
                        break;

                    case 12:
                        to_language     = "da";
                        recognized_text = inkView.Recognize(false);
                        if (!displayingFormatted && recognized_text != "" && recognized_text != "*Error*")
                        {
                            Translate(FormatLatex(recognized_text));
                        }
                        break;

                    case 13:
                        to_language     = "id";
                        recognized_text = inkView.Recognize(false);
                        if (!displayingFormatted && recognized_text != "" && recognized_text != "*Error*")
                        {
                            Translate(FormatLatex(recognized_text));
                        }
                        break;
                    }
                    WritePadAPI.recoFree();
                    WritePadAPI.recoInit();
                    WritePadAPI.initializeFlags();
                };
                translateActionSheet.ShowInView(View);
            };
            View.Add(translateButton);

            x                += (button_gap + button_width);
            printButton       = new UIButton(UIButtonType.Custom);
            printButton.Frame = new CGRect(x, height - bottom_gap, button_width, button_height);
            printButton.SetTitle("Save", UIControlState.Normal);
            printButton.Font = UIFont.SystemFontOfSize(button_font_size);
            printButton.SetTitleColor(UIColor.Blue, UIControlState.Normal);
            printButton.SetTitleColor(UIColor.White, UIControlState.Highlighted);
            printButton.AutoresizingMask = UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin;
            printButton.TouchUpInside   += (object sender, EventArgs e) => {
                if (displayingFormatted && formattedText.Text != "")
                {
                    var printInfo = UIPrintInfo.PrintInfo;

                    printInfo.OutputType = UIPrintInfoOutputType.General;
                    printInfo.JobName    = "Printing Tidied-Up Text";

                    UIPrintInteractionController printer = UIPrintInteractionController.SharedPrintController;

                    printer.PrintInfo      = printInfo;
                    printer.PrintingItem   = new NSString(formattedText.Text);
                    printer.ShowsPageRange = true;

                    printer.Present(true, PrintingCompleted);
                }
                else if (!displayingFormatted)
                {
                    switchViewButton.Hidden = true;
                    clearButton.Hidden      = true;
                    languageButton.Hidden   = true;
                    translateButton.Hidden  = true;
                    printButton.Hidden      = true;
                    UIImage data = UIScreen.MainScreen.Capture();
                    data.SaveToPhotosAlbum(null);
                    switchViewButton.Hidden = false;
                    clearButton.Hidden      = false;
                    languageButton.Hidden   = false;
                    translateButton.Hidden  = false;
                    printButton.Hidden      = false;
                }
            };
            View.Add(printButton);

            /*x += (button_gap + button_width);
             * rewriteButton = new UIButton (UIButtonType.Custom);
             * rewriteButton.Frame = new CGRect (x, height - bottom_gap, button_width, button_height);
             * rewriteButton.SetTitle ("Rewrite", UIControlState.Normal);
             * rewriteButton.Font = UIFont.SystemFontOfSize (button_font_size);
             * rewriteButton.SetTitleColor (UIColor.Blue, UIControlState.Normal);
             * rewriteButton.SetTitleColor (UIColor.White, UIControlState.Highlighted);
             * rewriteButton.AutoresizingMask = UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin;
             * rewriteButton.TouchUpInside += (object sender, EventArgs e) => {
             *      inkView.cleanView (true);
             *      if (translated_text != "")
             *      {
             *              formattedText.Hidden = true;
             *              inkView.Hidden = false;
             *              displayingFormatted = false;
             *              inkView.writeText (translated_text, (int)(width - button_gap * 2), (int)height);
             *      }
             * };
             * View.Add (rewriteButton);*/
        }
Пример #16
0
        public override void ViewDidAppear(bool animated)
        {
            this.appDelegate.tablePDFSearch = 0;
            UIBarButtonItem searchText = new UIBarButtonItem(UIBarButtonSystemItem.Search, (object sender, EventArgs e) =>
            {
                //searches for matching text inside pdf
                this.searchForText.Placeholder       = "Search...";
                this.searchForText.SpellCheckingType = UITextSpellCheckingType.No;
                this.searchForText.SearchBarStyle    = UISearchBarStyle.Prominent;
                this.searchForText.BarStyle          = UIBarStyle.Default;
                this.searchForText.ShowsCancelButton = true;
                this.NavigationItem.TitleView        = this.searchForText;

                this.searchForText.BecomeFirstResponder();
                this.searchForText.CancelButtonClicked += (object sender_2, EventArgs e_2) => {
                    //replaces the navigation item with the title text
                    this.searchForText.ResignFirstResponder();
                    this.NavigationItem.TitleView = null;
                    this.NavigationItem.Title     = "Viewer";
                };
            });

            UIBarButtonItem pageMode = new UIBarButtonItem("Page Mode", UIBarButtonItemStyle.Done, (object sender, EventArgs e) => {
                //page count is adjusted
                //creates a small table which adjusts the number of pages to render

                //an alert controller is best for this
                if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
                {
                    UIAlertController pageModeController = UIAlertController.Create("", "", UIAlertControllerStyle.ActionSheet);

                    UIAlertAction onePage = UIAlertAction.Create("Single Page", UIAlertActionStyle.Default, (UIAlertAction obj) =>
                    {
                        this.pdfWebReader.PaginationMode = UIWebPaginationMode.TopToBottom;
                        pageModeController.Dispose();
                    });

                    UIAlertAction continousPages = UIAlertAction.Create("Continuous", UIAlertActionStyle.Default, (UIAlertAction obj) =>
                    {
                        this.pdfWebReader.PaginationMode = UIWebPaginationMode.Unpaginated;
                        pageModeController.Dispose();
                    });

                    UIAlertAction denied = UIAlertAction.Create("Never Mind", UIAlertActionStyle.Cancel, (UIAlertAction obj) =>
                    {
                        pageModeController.Dispose();
                    });

                    pageModeController.AddAction(onePage);
                    pageModeController.AddAction(continousPages);
                    pageModeController.AddAction(denied);

                    if (this.PresentedViewController == null)
                    {
                        this.PresentViewController(pageModeController, true, null);
                    }
                    else
                    {
                        this.PresentedViewController.DismissViewController(true, () =>
                        {
                            this.PresentedViewController.Dispose();
                            this.PresentViewController(pageModeController, true, null);
                        });
                    }
                }
                else
                {
                    UIAlertController pageModeController = UIAlertController.Create("", "", UIAlertControllerStyle.Alert);

                    UIAlertAction onePage = UIAlertAction.Create("Single Page", UIAlertActionStyle.Default, (UIAlertAction obj) =>
                    {
                        this.pdfWebReader.PaginationMode = UIWebPaginationMode.TopToBottom;
                        pageModeController.Dispose();
                    });

                    UIAlertAction continousPages = UIAlertAction.Create("Full Screen", UIAlertActionStyle.Default, (UIAlertAction obj) =>
                    {
                        this.pdfWebReader.PaginationMode = UIWebPaginationMode.Unpaginated;
                        pageModeController.Dispose();
                    });

                    UIAlertAction denied = UIAlertAction.Create("Never Mind", UIAlertActionStyle.Cancel, (UIAlertAction obj) =>
                    {
                        pageModeController.Dispose();
                    });

                    pageModeController.AddAction(onePage);
                    pageModeController.AddAction(continousPages);
                    pageModeController.AddAction(denied);

                    if (this.PresentedViewController == null)
                    {
                        this.PresentViewController(pageModeController, true, null);
                    }
                    else
                    {
                        this.PresentedViewController.DismissViewController(true, () =>
                        {
                            this.PresentedViewController.Dispose();
                            this.PresentViewController(pageModeController, true, null);
                        });
                    }
                }
            });
            UIBarButtonItem share = new UIBarButtonItem(UIBarButtonSystemItem.Action, (sender, e) => {
                //introduces an action sheet. with the following options:

                /*
                 * allows the user to share file (which creates an activity controller where the user can choose how to share the file)
                 * allows updating to the cloud
                 * allows an option to open the document in another application of choice (UIDocumentInterationController)
                 * Print the document (In a nearby printer via AirPrint)
                 *
                 */
                if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Phone)
                {
                    UIAlertController shareModeController = UIAlertController.Create("", "", UIAlertControllerStyle.ActionSheet);

                    UIAlertAction shareFile = UIAlertAction.Create("Share File", UIAlertActionStyle.Default, (UIAlertAction obj) =>
                    {
                        var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                        var filePath  = Path.Combine(directory, this.appDelegate.pdfString);

                        NSUrl pdfURL   = NSUrl.FromFilename(filePath);
                        NSData pdfData = NSData.FromUrl(pdfURL);

                        NSObject[] dataToShare            = new NSObject[] { pdfURL };
                        UIActivityViewController activity = new UIActivityViewController(dataToShare, null);

                        //UIActivityType[] activityTypes = new UIActivityType[] { UIActivityType.Print, UIActivityType.SaveToCameraRoll };


                        if (this.PresentedViewController == null)
                        {
                            this.PresentViewController(activity, true, null);
                        }
                        else
                        {
                            this.PresentedViewController.DismissViewController(true, () => {
                                this.PresentedViewController.Dispose();
                                this.PresentViewController(activity, true, null);
                            });
                        }
                        shareModeController.Dispose();
                    });

                    UIAlertAction printDocument = UIAlertAction.Create("Print Document", UIAlertActionStyle.Default, (UIAlertAction obj) =>
                    {
                        var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                        var filePath  = Path.Combine(directory, this.appDelegate.pdfString);

                        NSUrl pdfURL                = NSUrl.FromFilename(filePath);
                        var printInformation        = UIPrintInfo.PrintInfo;
                        printInformation.OutputType = UIPrintInfoOutputType.General;
                        printInformation.JobName    = "Print Job";

                        var print            = UIPrintInteractionController.SharedPrintController;
                        print.PrintInfo      = printInformation;
                        print.PrintFormatter = this.pdfWebReader.ViewPrintFormatter;
                        print.PrintingItem   = pdfURL;
                        print.ShowsPageRange = true;

                        if (UIPrintInteractionController.CanPrint(pdfURL) == true)
                        {
                            print.Present(true, (UIPrintInteractionController printInteractionController, bool completed, NSError error) =>
                            {
                                if (error != null)
                                {
                                    print.Dismiss(true);
                                    errorPrinting("Print Error!", "Cannot print your document. Check if your printer is connected");
                                }
                                else
                                {
                                    Console.WriteLine("Printer success");
                                }
                            });
                        }
                        else
                        {
                            errorPrinting("Print Error!", "Cannot print your document. Check if your printer is connected");
                        }
                        shareModeController.Dispose();
                    });

                    UIAlertAction denied = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (UIAlertAction obj) =>
                    {
                        shareModeController.Dispose();
                    });

                    shareModeController.AddAction(shareFile);
                    shareModeController.AddAction(printDocument);
                    shareModeController.AddAction(denied);

                    if (this.PresentedViewController == null)
                    {
                        this.PresentViewController(shareModeController, true, null);
                    }
                    else
                    {
                        this.PresentedViewController.DismissViewController(true, () =>
                        {
                            this.PresentedViewController.Dispose();
                            this.PresentViewController(shareModeController, true, null);
                        });
                    }
                }
                else
                {
                    UIAlertController shareModeController = UIAlertController.Create("", "", UIAlertControllerStyle.Alert);

                    UIAlertAction shareFile = UIAlertAction.Create("Share File", UIAlertActionStyle.Default, (UIAlertAction obj) =>
                    {
                        var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                        var filePath  = Path.Combine(directory, this.appDelegate.pdfString);

                        NSUrl pdfURL   = NSUrl.FromFilename(filePath);
                        NSData pdfData = NSData.FromUrl(pdfURL);

                        NSObject[] dataToShare            = new NSObject[] { pdfURL };
                        UIActivityViewController activity = new UIActivityViewController(dataToShare, null);

                        //UIActivityType[] activityTypes = new UIActivityType[] { UIActivityType.Print, UIActivityType.SaveToCameraRoll };


                        if (this.PresentedViewController == null)
                        {
                            this.PresentViewController(activity, true, null);
                        }
                        else
                        {
                            this.PresentedViewController.DismissViewController(true, () =>
                            {
                                this.PresentedViewController.Dispose();
                                this.PresentViewController(activity, true, null);
                            });
                        }
                        shareModeController.Dispose();
                    });

                    UIAlertAction printDocument = UIAlertAction.Create("Print Document", UIAlertActionStyle.Default, (UIAlertAction obj) =>
                    {
                        var directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                        var filePath  = Path.Combine(directory, this.appDelegate.pdfString);

                        NSUrl pdfURL = NSUrl.FromFilename(filePath);

                        var printInformation        = UIPrintInfo.PrintInfo;
                        printInformation.OutputType = UIPrintInfoOutputType.General;
                        printInformation.JobName    = "Print Job";

                        var print            = UIPrintInteractionController.SharedPrintController;
                        print.PrintInfo      = printInformation;
                        print.PrintFormatter = this.pdfWebReader.ViewPrintFormatter;
                        print.PrintingItem   = pdfURL;

                        print.ShowsPageRange = true;
                        print.Present(true, (UIPrintInteractionController printInteractionController, bool completed, NSError error) =>
                        {
                            if (error != null)
                            {
                                print.Dismiss(true);
                                errorPrinting("Print Error!", "Cannot print your document. Check if your printer is connected");
                            }
                            else
                            {
                                Console.WriteLine("Printer success");
                            }
                        });

                        shareModeController.Dispose();
                    });

                    UIAlertAction denied = UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, (UIAlertAction obj) =>
                    {
                        shareModeController.Dispose();
                    });

                    shareModeController.AddAction(shareFile);
                    shareModeController.AddAction(printDocument);
                    shareModeController.AddAction(denied);

                    if (this.PresentedViewController == null)
                    {
                        this.PresentViewController(shareModeController, true, null);
                    }
                    else
                    {
                        this.PresentedViewController.DismissViewController(true, () =>
                        {
                            this.PresentedViewController.Dispose();
                            this.PresentViewController(shareModeController, true, null);
                        });
                    }
                }
            });
            UIBarButtonItem writeComment = new UIBarButtonItem("Comment", UIBarButtonItemStyle.Done, (sender, e) => {
                //adjusts the toolbar items with drawing items used for drawing items on the PDF view controller
            });

            this.NavigationController.SetToolbarHidden(false, true);
            UIBarButtonItem space_1 = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace, null);
            UIBarButtonItem space_2 = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace, null);

            this.NavigationController.Toolbar.Items = new UIBarButtonItem[] { searchText, space_1, space_2, share };
        }
		void PrintingCompleted (UIPrintInteractionController controller, bool completed, NSError error)
		{

		}
        public void Print(object sender, EventArgs args)
        {
            UIPrintInteractionController controller = UIPrintInteractionController.SharedPrintController;

            if (controller == null)
            {
                Console.WriteLine("Couldn't get shared UIPrintInteractionController");
                return;
            }

            controller.CutLengthForPaper = delegate(UIPrintInteractionController printController, UIPrintPaper paper) {
                // Create a font with arbitrary size so that you can calculate the approximate
                // font points per screen point for the height of the text.
                UIFont font = textformatter.Font;

                NSString           str        = new NSString(textField.Text);
                UIStringAttributes attributes = new UIStringAttributes();
                attributes.Font = font;
                CGSize size = str.GetSizeUsingAttributes(attributes);

                nfloat approximateFontPointPerScreenPoint = font.PointSize / size.Height;

                // Create a new font using a size  that will fill the width of the paper
                font = SelectFont((float)(paper.PrintableRect.Size.Width * approximateFontPointPerScreenPoint));

                // Calculate the height and width of the text with the final font size
                attributes.Font = font;
                CGSize finalTextSize = str.GetSizeUsingAttributes(attributes);

                // Set the UISimpleTextFormatter font to the font with the size calculated
                textformatter.Font = font;

                // Calculate the margins of the roll. Roll printers may have unprintable areas
                // before and after the cut.  We must add this to our cut length to ensure the
                // printable area has enough room for our text.
                nfloat lengthOfMargins = paper.PaperSize.Height - paper.PrintableRect.Size.Height;

                // The cut length is the width of the text, plus margins, plus some padding
                return(finalTextSize.Width + lengthOfMargins + paper.PrintableRect.Size.Width * PaddingFactor);
            };

            UIPrintInfo printInfo = UIPrintInfo.PrintInfo;

            printInfo.OutputType  = UIPrintInfoOutputType.General;
            printInfo.Orientation = UIPrintInfoOrientation.Landscape;
            printInfo.JobName     = textField.Text;

            textformatter = new UISimpleTextPrintFormatter(textField.Text)
            {
                Color = SelectedColor,
                Font  = SelectFont()
            };

            controller.PrintInfo      = printInfo;
            controller.PrintFormatter = textformatter;

            if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
            {
                controller.PresentFromRectInView(printButton.Frame, View, true, PrintingComplete);
            }
            else
            {
                controller.Present(true, PrintingComplete);
            }
        }
 void PrintingCompleted(UIPrintInteractionController controller, bool completed, NSError error)
 {
 }