简体   繁体   English

如何使用手机默认打印机功能在Xamarin Android中打印从WebView打开的PDF内容

[英]How to use phone default printer function to print the content of PDF opened from WebView in Xamarin Android

Can any one help me with the problem, to print the url content.任何人都可以帮助我解决这个问题,打印 url 内容。 I am opening the PDF file in a web view of my application and then trying to print the document from there by placing separate button for printing.我正在我的应用程序的 Web 视图中打开 PDF 文件,然后尝试通过放置单独的打印按钮从那里打印文档。 Please look at the code below.请看下面的代码。

    [Activity(Label = "PdfView")]
    public class PdfView : Activity
    {
        public static PdfView _context;
        Android.Content.Res.Resources res;
        private static string ErrorTitle, ErrorMsg;
        private static ProgressBar progressBar;

        WebView mWebView, Web_Print;
        RelativeLayout LL_Print,LL_input;
        string MyUrl;
        private WebClient _webClient = new WebClient();
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            _context = this;
            res = _context.Resources;
            SetContentView(Resource.Layout.web_pdf);
            ErrorTitle = res.GetString(Resource.String.error_title);
            ErrorMsg = res.GetString(Resource.String.Somethingwentwrong);
            progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar1);
            LL_Print = FindViewById<RelativeLayout>(Resource.Id.LL_Print);
            LL_input = FindViewById<RelativeLayout>(Resource.Id.LL_input);
            Web_Print = FindViewById<WebView>(Resource.Id.Web_Print);
            Web_Print.Visibility = ViewStates.Gone;
            LL_Print.Visibility = ViewStates.Gone;
            var customWebViewClient = new WebViewLoaderClient();
            mWebView = FindViewById<WebView>(Resource.Id.Web);
            mWebView.Download += MWebview_Download;               
            mWebView.Settings.JavaScriptEnabled = true;
            mWebView.Settings.BuiltInZoomControls = true;
            mWebView.SetWebViewClient(customWebViewClient);
            mWebView.SetWebChromeClient(new WebChromeClient());
            String myPdfUrl = APIConstants.InvoicePdfUrl;
            MyUrl = "http://docs.google.com/gview?embedded=true&url=" + myPdfUrl;
            mWebView.LoadUrl(MyUrl);

            InitComonents();
        }

        private void MWebview_Download(object sender, DownloadEventArgs e)
        {
            mWebView.Visibility = ViewStates.Gone;
            LL_input.Visibility = ViewStates.Gone;
            LL_Print.Visibility = ViewStates.Visible;
            Web_Print.Visibility = ViewStates.Visible;
            var Url = e.Url;
            CustomWebViewClient client = new CustomWebViewClient(this);
            Web_Print.SetWebViewClient(client);
            Web_Print.SetWebChromeClient(new WebChromeClient());
            Web_Print.Settings.JavaScriptEnabled = true;
            Web_Print.LoadUrl(Url);
            Web_Print.Settings.UseWideViewPort = true;
            Web_Print.Settings.LoadWithOverviewMode = true;
        }


        #region // Initializing widgets
        public void InitComonents()
        {
            try
            {
                LinearLayout img_viw = FindViewById<LinearLayout>(Resource.Id.img_WV_back);
                LinearLayout img_viw_Home = FindViewById<LinearLayout>(Resource.Id.img_WV_home);

            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }
        #endregion

        #region // Webview client
        public class WebViewLoaderClient : WebViewClient
        {
            public event EventHandler<bool> OnPageLoaded;
            public override bool ShouldOverrideUrlLoading(WebView view, string url)
            {
                view.LoadUrl(url);
                return true;
            }
            public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon)
            {
                base.OnPageStarted(view, url, favicon);
                progressBar.Visibility = ViewStates.Visible;
            }
            public override void OnPageFinished(WebView view, string url)
            {
                base.OnPageFinished(view, url);
                progressBar.Visibility = ViewStates.Gone;
            }
            public override void OnReceivedError(WebView view, ClientError errorCode, string description, string failingUrl)
            {
                base.OnReceivedError(view, errorCode, description, failingUrl);
                view.Visibility = ViewStates.Gone;
                Error();
            }
        }
        class MonkeyWebViewClient : WebViewClient
        {
            public override bool ShouldOverrideUrlLoading(WebView view, string url)
            {
                view.LoadUrl(url);
                return true;
            }
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
            {
                view.LoadUrl("file:///android_asset/myerrorpage.html");
            }
        }
        #endregion


        #region Error Message for Web View Error
        public static void Error()
        {
            AlertDialog.Builder alert = new AlertDialog.Builder(_context);
            alert.SetTitle(ErrorTitle);
            alert.SetMessage(ErrorMsg);
            alert.SetPositiveButton(Resource.String.ok, (senderAlert, args) =>
            {
                _context.Finish();
            });
            alert.SetCancelable(false);
            Dialog dialog = alert.Create();
            dialog.Show();
        }

        public void doWebViewPrint(string url)
        {
            PrintDocumentAdapter adapter;
            if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
                adapter = mWebView.CreatePrintDocumentAdapter("test");
            else
                adapter = mWebView.CreatePrintDocumentAdapter();
            var printMgr = (PrintManager)GetSystemService(PrintService);
            printMgr.Print("printTest", adapter, null);
        }
        #endregion
    }

    public class CustomWebViewClient : WebViewClient
    {
        private PdfView myActivity;
        public bool shouldOverrideUrlLoading(WebView view, string url)
        {
            view.LoadUrl(url);
            return false;
        }
        public override void OnPageFinished(WebView view, string url)
        {
            Log.Debug("PRINT", "page finished loading " + url);
            myActivity.doWebViewPrint(url);
            //CreateWebPrintJob(view);
            base.OnPageFinished(view, url);
        }

        private void CreateWebPrintJob(WebView view)
        {
            throw new NotImplementedException();
        }

        public CustomWebViewClient(PdfView activity)
        {
            myActivity = activity;
        }
    }
}

This is able show the content of the PDF and open the printer function but the content of the PDF is not able to view in the printer function as preview ie, getting me as follows这可以显示PDF的内容并打开打印机功能,但无法在打印机功能中查看PDF的内容作为预览,即,让我如下打印机默认值

So, Can any one help me with this problem to rectify and able to get the PDF content viewed in the web to print it.因此,任何人都可以帮助我解决此问题以纠正并能够在网络中查看 PDF 内容以进行打印。

Please see the following code which made it possible to print:: The complete game changer here is scale calculation,请参阅以下使打印成为可能的代码:这里的完整游戏规则改变者是比例计算,

.
.
.
.
.
.
.
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            _context = this;
            res = _context.Resources;
            SetContentView(Resource.Layout.xxxxxxxxxxxxxxxx);
            var customWebViewClient = new WebViewLoaderClient();
            mWebView = FindViewById<WebView>(Resource.Id.Web);
            //mWebView.Download += MWebview_Download;
            UserLoginDetailList = UserInfoDBServices.getUserLoginDetailsfromDBfordroid();
            ObjLangList = UserInfoDBServices.GetCurrentLanguageListfordroid();
            mWebView.Settings.JavaScriptEnabled = true;
            mWebView.Settings.BuiltInZoomControls = true;
            mWebView.SetWebViewClient(customWebViewClient);
            String myPdfUrl = APIConstants.InvoicePdfUrl;
            MyUrl = "http://docs.google.com/gview?embedded=true&url=" + myPdfUrl;//Here in myPdfUrl variable place the url of the pdf you are getting from your server
            mWebView.LoadUrl(MyUrl);
            InitComonents();
        }
        #region // Initializing widgets
        public void InitComonents()
        {
            try
            {
                Print = FindViewById<LinearLayout>(Resource.Id.ll_TNP_Pirnt);
                Print.Visibility = ViewStates.Visible;
                Print.Click += delegate
                  {
                      LL_Print.Clickable = false;
                      var printManager = (PrintManager)GetSystemService(Context.PrintService);
                      var content = FindViewById<LinearLayout>(Resource.Id.LL_input);
                      var printAdapter = new GenericPrintAdapter(this, content);

                      printManager.Print("MyPrintJob", printAdapter, null);
                  };
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
        }
        #endregion
        public class GenericPrintAdapter:PrintDocumentAdapter
        {
            View view;
            Context context;
            PrintedPdfDocument document;
            float scale;
            private DownloadPdfView downloadPdfView;
            private RelativeLayout content;

            public GenericPrintAdapter(DownloadPdfView downloadPdfView, View view)
            {
                this.downloadPdfView = downloadPdfView;
                this.view = view;
            }

            public override void OnLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras)
            {
                try
                {
                    document = new PrintedPdfDocument(context, newAttributes);

                    CalculateScale(newAttributes);

                    var printInfo = new PrintDocumentInfo
                        .Builder("Invoice.pdf")
                        .SetContentType(PrintContentType.Document)
                        .SetPageCount(1)
                        .Build();

                    callback.OnLayoutFinished(printInfo, true);
                }
                catch(Exception ex)
                {
                    ex.Message.ToString();
                }

            }

            public override void OnWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback)
            {

                try
                {
                    PrintedPdfDocument.Page page = document.StartPage(0);

                    page.Canvas.Scale(scale, scale);

                    view.Draw(page.Canvas);

                    document.FinishPage(page);

                    WritePrintedPdfDoc(destination);

                    document.Close();

                    document.Dispose();

                    callback.OnWriteFinished(pages);
                }
                catch (Exception ex)
                {
                    ex.Message.ToString();
                }

            }
            void CalculateScale(PrintAttributes newAttributes)
            {
                try
                {
                    int dpi = Math.Max(newAttributes.GetResolution().HorizontalDpi, newAttributes.GetResolution().VerticalDpi);

                    int leftMargin = (int)(dpi * (float)newAttributes.MinMargins.LeftMils / 1000);
                    int rightMargin = (int)(dpi * (float)newAttributes.MinMargins.RightMils / 1000);
                    int topMargin = (int)(dpi * (float)newAttributes.MinMargins.TopMils / 1000);
                    int bottomMargin = (int)(dpi * (float)newAttributes.MinMargins.BottomMils / 1000);

                    int w = (int)(dpi * (float)newAttributes.GetMediaSize().WidthMils / 3500) - leftMargin - rightMargin;
                    int h = (int)(dpi * (float)newAttributes.GetMediaSize().HeightMils / 3500) - topMargin - bottomMargin;

                    scale = Math.Min((float)document.PageContentRect.Width() / w, (float)document.PageContentRect.Height() / h);
                }
                catch (Exception ex)
                {
                    ex.Message.ToString();
                }

            }
            void WritePrintedPdfDoc(ParcelFileDescriptor destination)
            {
                try
                {
                    var javaStream = new Java.IO.FileOutputStream(destination.FileDescriptor);
                    var osi = new OutputStreamInvoker(javaStream);
                    using (var mem = new MemoryStream())
                    {
                        document.WriteTo(mem);
                        var bytes = mem.ToArray();
                        osi.Write(bytes, 0, bytes.Length);
                    }
                }
                catch (Exception ex)
                {
                    ex.Message.ToString();
                }
            }
        }

        #region // Webview client
        public class WebViewLoaderClient : WebViewClient
        {
            public event EventHandler<bool> OnPageLoaded;
            public override bool ShouldOverrideUrlLoading(WebView view, string url)
            {
                view.LoadUrl(url);
                return true;
            }
            public override void OnPageStarted(WebView view, string url, Android.Graphics.Bitmap favicon)
            {
                base.OnPageStarted(view, url, favicon);
                progressBar.Visibility = ViewStates.Visible;
            }
            public override void OnPageFinished(WebView view, string url)
            {
                base.OnPageFinished(view, url);
                progressBar.Visibility = ViewStates.Gone;
            }
            public override void OnReceivedError(WebView view, ClientError errorCode, string description, string failingUrl)
            {
                base.OnReceivedError(view, errorCode, description, failingUrl);
                view.Visibility = ViewStates.Gone;
                Error();
            }
        }
        class MonkeyWebViewClient : WebViewClient
        {
            public override bool ShouldOverrideUrlLoading(WebView view, string url)
            {
                view.LoadUrl(url);
                return true;
            }
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
            {
                view.LoadUrl("file:///android_asset/myerrorpage.html");
            }
        }
        #endregion

        #region Error Message for Web View Error
        public static void Error()
        {
            AlertDialog.Builder alert = new AlertDialog.Builder(_context);
            alert.SetTitle(ErrorTitle);
            alert.SetMessage(ErrorMsg);
            alert.SetPositiveButton(Resource.String.ok, (senderAlert, args) =>
            {
                _context.Finish();
            });
            alert.SetCancelable(false);
            Dialog dialog = alert.Create();
            dialog.Show();
        }
        #endregion
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 android如何使用蓝牙打印机打印WebView内容 - how android use BlueTooth printer print the WebView content 如何从android webview推送打印到蓝牙热敏打印机? - How to push print to bluetooth thermal printer from android webview? Xamarin:如何从Android设备打印到点矩阵打印机? - Xamarin: How to print from Android device to dot matrix printer? 如何从Android手机向Bluetooth打印机打印带有文本的图像? - How to print image with text from android phone to Bluetooth printer.? Xamarin Android WebView 下载内联pdf内容 - Xamarin Android WebView download inline pdf content 如何从无线打印机打印 pdf 文件? - How to print the pdf file from wireless printer? 从WebView打开pdf文件时如何使用MuPDF库打开pdf文件 - How to use the MuPDF library to open pdf files when a pdf file is opened from webview 如何在 Z5A98E2840FD0141780D854E48C608D 中显示来自 xamarin android 按钮的警报 function - How to display alert function from xamarin android button in webview 如何使用Brother HL-1110系列打印机从Android应用程序打印pdf - How to print pdf from my Android app with Brother HL-1110 Series Printer 如何从Android设备打印PDF,图像和HTML文件到wifi上的打印机? - How to print PDF, image and HTML documents from android device to a printer on wifi?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM