示例#1
0
        public override async Task <bool> PrintFromURLAsync(string url, PrintJobConfiguration printJobConfiguration)
        {
            bool result = false;

            try
            {
                if (PrintFromURLAsyncSupported)
                {
                    WebViewPrintClientSubclass webViewClientSubclass = new WebViewPrintClientSubclass(url, printJobConfiguration); // TODO - check that this is disposed
                    webViewClientSubclass.Run();
                    result = true;
                }
            }
            catch (Java.Lang.Exception jlex)
            {
                await PrintStatusReporting.ReportExceptionSilentlyAsync(jlex);
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (System.Exception ex)
            {
                await PrintStatusReporting.ReportExceptionAsync(ex);
            }
#pragma warning restore CA1031 // Do not catch general exception types

            return(result);
        }
示例#2
0
        public override async Task <bool> PrintPdfFromStreamAsync(
            Stream inputStream,
            PrintJobConfiguration config)
        {
            bool result = false;

            try
            {
                if (PrintPdfFromStreamAsyncSupported)
                {
                    PdfPrintJob printJob = new PdfPrintJob(config, inputStream);
                    await printJob.PrintAsync();

                    result = true;
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
            {
                await PrintStatusReporting.ReportExceptionAsync(ex);

                result = false;
            }
#pragma warning restore CA1031 // Do not catch general exception types

            return(result);
        }
示例#3
0
        /// <summary>
        /// Print the contents of a WebView
        /// </summary>
        /// <param name="parentPage">The page that the WebView is shown on.</param>
        /// <param name="webView">The Xamarin.Forms WebView.</param>
        /// <param name="webViewAdditionFunctions">Additional functions</param>
        /// <param name="printJobConfiguration">Configuration information for the print job.</param>
        /// <returns>true if attempting print, false otherwise.</returns>
        public override async Task <bool> PrintWebViewAsync(
            Page parentPage,
            WebView webView,
            IWebViewAdditionalFunctions webViewAdditionFunctions,
            PrintJobConfiguration printJobConfiguration)
        {
            bool result = false;

            try
            {
                // TODO - get rid of use of UIWebView as deprecated by Apple
                // See https://forums.xamarin.com/discussion/168620/itms-90338-non-public-api-usage-apple-rejected-my-app-xamarin#latest

                if (PrintWebViewAsyncSupported &&
                    (webViewAdditionFunctions?.NativeControl is UIWebView nativeWebView))
                {
                    using (nativeWebView)
                    {
                        result = await PrintUIViewAsync(nativeWebView, printJobConfiguration);
                    }
                }
            }
#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

            return(result);
        }
示例#4
0
        public override async Task <bool> PrintFromURLAsync(string url, PrintJobConfiguration printJobConfiguration) // was string jobName, bool enablePrintPreview = true)
        {
            bool result = false;

            try
            {
                if (PrintFromURLAsyncSupported)
                {
                    if (!(url is null))
                    {
                        UriPrintJob printJob = new UriPrintJob(printJobConfiguration, new Uri(url));
                        await printJob.PrintAsync();

                        result = true;
                    }
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
            {
                await PrintStatusReporting.ReportExceptionAsync(ex);

                result = false;
            }
#pragma warning restore CA1031 // Do not catch general exception types

            // TODO - does this want to be here??? printJob?.UnwireAllEvents();

            return(result);
        }
示例#5
0
        public override async Task <bool> PrintImageFromByteArrayAsync(
            byte[] content,
            PrintJobConfiguration config)
        {
            bool result = false;

            try
            {
                if (PrintImageFromByteArrayAsyncSupported)
                {
                    ImagePrintJob printJob = new ImagePrintJob(config, content);
                    await printJob.PrintAsync();

                    result = true;
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
            {
                await PrintStatusReporting.ReportExceptionAsync(ex);

                result = false;
            }
#pragma warning restore CA1031 // Do not catch general exception types

            return(result);
        }
示例#6
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
        }
示例#7
0
        public override async Task <bool> PrintImageFromByteArrayAsync(byte[] content, PrintJobConfiguration printJobConfiguration)
        {
            // based on https://github.com/bushbert/XamarinPCLPrinting/blob/master/PCLPrintExample/PCLPrintExample/PCLPrintExample.Android/Print.cs

            bool result = false;

            try
            {
                if (PrintImageFromByteArrayAsyncSupported)
                {
                    //using (
                    Stream inputStream = new MemoryStream(content); //)
                    {
                        PrintServiceAndroidHelper.PrintImageFromStream(inputStream, printJobConfiguration);
                        result = true;
                    }
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (System.Exception ex)
            {
                await PrintStatusReporting.ReportExceptionAsync(ex);
            }
#pragma warning restore CA1031 // Do not catch general exception types

            return(result);
        }
示例#8
0
        public override async Task <bool> PrintWebViewAsync(
            Page parentPage,
            WebView webView,
            IWebViewAdditionalFunctions webViewAdditionFunctions,
            PrintJobConfiguration printJobConfiguration)
        {
            bool result = false;

            try
            {
                if (PrintWebViewAsyncSupported &&
                    (webViewAdditionFunctions?.NativeControl is Android.Webkit.WebView nativeWebView))
                {
                    PrintServiceAndroidHelper.PrintFromWebView(nativeWebView, printJobConfiguration);
                    result = true;
                }
            }
            catch (Java.Lang.Exception jlex)
            {
                await PrintStatusReporting.ReportExceptionSilentlyAsync(jlex);
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (System.Exception ex)
            {
                await PrintStatusReporting.ReportExceptionAsync(ex);
            }
#pragma warning restore CA1031 // Do not catch general exception types

            return(result);
        }
示例#9
0
        /// <summary>
        ///
        /// </summary>
        /// <returns>true if no immediate errors detected, false if an immediate error detected. Note that a true return value does not mean that printing completed successfully, just that it didn't fail immediately</returns>
        protected async Task <bool> RegisterForPrintingAsync()
        {
            try
            {
                _printDocument       = new Windows.UI.Xaml.Printing.PrintDocument();
                _printDocumentSource = _printDocument.DocumentSource;

                _printDocument.Paginate       += CreatePrintPreviewPages;
                _printDocument.GetPreviewPage += GetPrintPreviewPage;
                _printDocument.AddPages       += AddPrintPages;
#if DEBUG
                IncrementAddPagesCount();
                IncrementGetPreviewPageCount();
                IncrementPaginateCount();
#endif

                _printManager = Windows.Graphics.Printing.PrintManager.GetForCurrentView();
                if (!(_printManager is null))
                {
                    PrintManagerHelper.Instance.SetPrintTaskRequestedHandler(
                        _printManager,
                        PrintTaskRequested);
                    return(true);
                }
            }
#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

            if (!(_printDocument is null))
            {
                _printDocument.Paginate       -= CreatePrintPreviewPages;
                _printDocument.GetPreviewPage -= GetPrintPreviewPage;
                _printDocument.AddPages       -= AddPrintPages;
            }

#if DEBUG
            DecrementPaginateCount();
            DecrementGetPreviewPageCount();
            DecrementAddPagesCount();
#endif

            await PrintStatusReporting.ReportErrorAsync(
                CrossPrinting.PrintingMessages.FailedToRegisterForPrinting);

            return(false);
        }
示例#10
0
        /// <summary>
        /// Wraps a function in a try/catch block, reporting back any
        /// exception on the UI thread through the PrintStatusReporting class.
        /// </summary>
        /// <param name="func"></param>
        internal static void SafeBlock(
            BlockDelegate func)
        {
            try
            {
                func();
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
            {
                Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
                {
                    await PrintStatusReporting.ReportExceptionAsync(ex);
                });
            }
#pragma warning restore CA1031 // Do not catch general exception types
        }
示例#11
0
        /// <summary>
        /// Show Print Preview UI
        /// </summary>
        /// <returns>Task that the caller is expected to await</returns>
        protected async Task ShowPrintApiAsync()
        {
            try
            {
                if (await RegisterForPrintingAsync())
                {
                    bool showprint = await Windows.Graphics.Printing.PrintManager.ShowPrintUIAsync();
                }
                else
                {
                    UnwireAllEvents();
                }
            }
#pragma warning disable CS0168 // Variable is declared but never used
            catch (System.IO.FileNotFoundException fnfex)
#pragma warning restore CS0168 // Variable is declared but never used
            {
                UnwireAllEvents();
                await PrintStatusReporting.ReportInfoAsync(
                    CrossPrinting.PrintingMessages.PrinterServiceBusy);

                return;
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
            {
                if ((ex.Message != null) && (ex.Message.Contains("0x80010115")))
                {
                    // {"OLE has sent a request and is waiting for a reply. (Exception from HRESULT: 0x80010115)"}

                    await PrintStatusReporting.ReportInfoAsync(
                        CrossPrinting.PrintingMessages.AwaitingResponse);

                    UnwireAllEvents();
                    return;
                }
                else
                {
                    await PrintStatusReporting.ReportExceptionAsync(ex);

                    UnwireAllEvents();
                    return;
                }
            }
#pragma warning restore CA1031 // Do not catch general exception types
        }
示例#12
0
        private async Task <bool> PrintFileFromStreamAsync(Stream inputStream, PrintJobConfiguration printJobConfiguration)
        {
            bool result = false;

            try
            {
                string documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                string library   = Path.Combine(documents, "..", "Library");
                string filePath  = Path.Combine(library, printJobConfiguration.JobName);

                try
                {
                    File.Delete(filePath);
                }
#pragma warning disable CA1031 // Do not catch general exception types
                catch
                {
                    // no-op
                }
#pragma warning restore CA1031 // Do not catch general exception types

                using (MemoryStream tempStream = new MemoryStream())
                {
                    inputStream.Position = 0;
                    inputStream.CopyTo(tempStream);
                    File.WriteAllBytes(filePath, tempStream.ToArray());
                }

                NSUrl url = NSUrl.FromFilename(filePath);
                using (url)
                {
                    result = await PrintObjectAsync(url, printJobConfiguration);
                }
            }
#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

            return(result);
        }
示例#13
0
        public override async Task <bool> PrintImageFromStreamAsync(Stream stream, PrintJobConfiguration printJobConfiguration)
        {
            try
            {
                if (PrintImageFromStreamAsyncSupported)
                {
                    return(await PrintImageFromData(
                               NSData.FromStream(stream),
                               printJobConfiguration));
                }
            }
#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

            return(false);
        }
示例#14
0
        /// <summary>
        /// Event handler that shows the Print Preview dialog once the DOM content has been loaded for the URI
        /// </summary>
        /// <param name="sender">The sender</param>
        /// <param name="args">The event args related to the DOM content loading completion</param>
        private async void NativeWebViewDOMContentLoaded(
#pragma warning disable IDE0060 // Remove unused parameter
            Windows.UI.Xaml.Controls.WebView sender,
            Windows.UI.Xaml.Controls.WebViewDOMContentLoadedEventArgs args)
#pragma warning restore IDE0060 // Remove unused parameter
        {
            try
            {
                await ShowPrintApiAsync();
            }
#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
            finally
            {
                Unwire();
            }
        }
示例#15
0
        public override async Task <bool> PrintImageFromStreamAsync(Stream inputStream, PrintJobConfiguration printJobConfiguration)
        {
            bool result = false;

            try
            {
                if (PrintImageFromStreamAsyncSupported)
                {
                    PrintServiceAndroidHelper.PrintImageFromStream(inputStream, printJobConfiguration);
                    result = true;
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (System.Exception ex)
            {
                await PrintStatusReporting.ReportExceptionAsync(ex);
            }
#pragma warning restore CA1031 // Do not catch general exception types

            return(result);
        }
示例#16
0
        public override async Task <bool> PrintFromURLAsync(string url, PrintJobConfiguration printJobConfiguration)
        {
            bool result = false;

            try
            {
                if (PrintFromURLAsyncSupported)
                {
                    using (NSUrl nsUrl = NSUrl.FromString(url))
                    {
                        result = await PrintObjectAsync(nsUrl, printJobConfiguration);
                    }
                }
            }
#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

            return(result);
        }
示例#17
0
        public override async Task <bool> PrintWebViewAsync(
            Page page,
            WebView webView,
            IWebViewAdditionalFunctions webViewAdditionFunctions,
            PrintJobConfiguration config)
        {
            bool result = false;

            try
            {
                if (PrintWebViewAsyncSupported)
                {
                    if (!(webViewAdditionFunctions is null))
                    {
                        await webViewAdditionFunctions.WaitForViewToBeInNativeLayout(page, 10, 100);

                        WebViewPrintJob printJob = new WebViewPrintJob(config, webViewAdditionFunctions);
                        //WebViewPrintJob printJob = new WebViewPrintJob(config, html);
                        await printJob.PrintAsync();

                        result = true;
                    }
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
            {
                await PrintStatusReporting.ReportExceptionAsync(ex);

                result = false;
            }
#pragma warning restore CA1031 // Do not catch general exception types

            // TODO - does this want to be here??? printJob?.UnwireAllEvents();

            return(result);
        }
示例#18
0
        /// <summary>
        /// AddPages event handler
        /// </summary>
        /// <param name="sender">The sender</param>
        /// <param name="e">AddPages event args</param>
        private async void AddPrintPages(
            object sender,
            Windows.UI.Xaml.Printing.AddPagesEventArgs e)
        {
            try
            {
                // based on https://docs.microsoft.com/en-us/windows/uwp/devices-sensors/print-from-your-app

                if ((!_printJobConfiguration.AllowPageRangeSpecification) ||
                    (e.PrintTaskOptions.CustomPageRanges.Count == 0))
                {
                    if (!_printJobConfiguration.PreferPrintPreview)
                    {
                        await GeneratePagesAsync();
                    }

                    // Loop over all of the preview pages and add each one to add each page to be printed
                    if ((sender is Windows.UI.Xaml.Printing.PrintDocument printDoc) &&
                        (_printPreviewPages != null))
                    {
                        // Note that _printDocument.Equals(printDoc)
                        // so possible optimisation/simplification here

                        foreach (Windows.UI.Xaml.UIElement previewPage in _printPreviewPages)
                        {
                            _printDocument.AddPage(previewPage);
                        }

                        _printDocument.AddPagesComplete();
                    }
                }
                else
                {
                    // Print only the pages chosen by the user.
                    //
                    // The "Current page" option is a special case of "Custom set of pages".
                    // In case the user selects the "Current page" option, the PrintDialog
                    // will turn that into a CustomPageRanges containing the page that the user was looking at.
                    // If the user typed in an indefinite range such as "6-", the LastPageNumber value
                    // will be whatever this sample app last passed into the PrintDocument.SetPreviewPageCount API.
                    IList <Windows.Graphics.Printing.PrintPageRange> customPageRanges = e.PrintTaskOptions.CustomPageRanges;
                    foreach (Windows.Graphics.Printing.PrintPageRange pageRange in customPageRanges)
                    {
                        // The user may type in a page number that is not present in the document.
                        // In this case, we just ignore those pages, hence the checks
                        // (pageRange.FirstPageNumber <= printPreviewPages.Count) and (i <= printPreviewPages.Count).
                        //
                        // If the user types the same page multiple times, it will be printed multiple times
                        // (e.g 3-4;1;1 will print pages 3 and 4 followed by two copies of page 1)
                        if (pageRange.FirstPageNumber <= _printPreviewPages.Count)
                        {
                            for (int i = pageRange.FirstPageNumber; (i <= pageRange.LastPageNumber) && (i <= _printPreviewPages.Count); i++)
                            {
                                // Subtract 1 because page numbers are 1-based, but our list is 0-based.
                                _printDocument.AddPage(_printPreviewPages[i - 1]);
                            }
                        }
                    }

                    _printDocument.AddPagesComplete();
                }
            }
#pragma warning disable CA1031 // Do not catch general exception types
            catch (Exception ex)
            {
                if (sender is Windows.UI.Xaml.Printing.PrintDocument printDoc)
                {
                    printDoc.InvalidatePreview();
                }

                PrintManagerHelper.Instance.ClearPrintTaskRequestedHandler(_printManager);
                //_printManager.PrintTaskRequested -= PrintTaskRequested;
                await PrintStatusReporting.ReportExceptionAsync(ex);
            }
#pragma warning restore CA1031 // Do not catch general exception types
        }