Print a web view in MAUI

Manickam, Suraj 320 Reputation points
2023-11-17T11:37:49.67+00:00

I have a web view where the user has an option to preview and print it on click of a button , In xamarin.forms we used Print Manager and Print Document Adapter to achieve this but the same does not seem to be working in MAUI , I checked the docs and there were no mention of the same !

Developer technologies .NET .NET MAUI
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,126 Reputation points Microsoft External Staff
    2023-11-21T02:59:03.1866667+00:00

    Hello,

    In MAUI, you can migrate this Forms method to MAUI by following the steps below.

    Step 1. Create a MainAcceleration instance for system service.

    public class MainActivity : MauiAppCompatActivity {
        public static MainActivity Instance { get; private set; }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            Instance = this;
        }
    }
    

    Step 2. Create a static class under the Platforms\Android file to implement this method.

    public static class PrintHelper
    {
        public static void Print(WebView webView)
        {
            var droidViewToPrint = webView.Handler.PlatformView as Android.Webkit.WebView;
            if (droidViewToPrint != null )
            {
                var version = Android.OS.Build.VERSION.SdkInt;
    
                if(version >= Android.OS.BuildVersionCodes.Kitkat)
                {
                    var printMgr = MainActivity.Instance.GetSystemService(Context.PrintService) as PrintManager;
    
                    PrintDocumentAdapter printDocumentAdapter;
                    string jobName = "Print";
    
                    if(version>=Android.OS.BuildVersionCodes.Lollipop)
                    {
                        printDocumentAdapter = droidViewToPrint.CreatePrintDocumentAdapter(jobName);
    
                    }
                    else
                    {
                        printDocumentAdapter = droidViewToPrint.CreatePrintDocumentAdapter();
                    }
                    printMgr.Print("Print", printDocumentAdapter, null);
                }
            }
        }
    }
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.