androidprintingandroid-4.4-kitkatandroid-print-framework

How do I print a WebView using KitKat 4.4 print API via reflection?


I need to support printing on KitKat devices but my target SDK is 13 (changing is not an option).

Specifically I need to print a webview.

This is the API for printing a webview: http://developer.android.com/training/printing/html-docs.html


Solution

  • It's an old one but printing is kind of usefull so this could be good to work correctly. (Without reflection ;))

    A better way to work with devices version. No try-catch needed, just need to add some messages before the return or you just hide the button/menu/... depending on the same condition.

    @TargetApi(Build.VERSION_CODES.KITKAT)
        private void createWebPrintJob(WebView webView) {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) 
                return;
    
            // Get a PrintManager instance
            PrintManager printManager = (PrintManager) getSystemService(Context.PRINT_SERVICE);
    
            // Get a print adapter instance
            PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter();
    
            // Create a print job with name and adapter instance
            String jobName = getString(R.string.app_name) + " Document";
            printManager.print(jobName, printAdapter,
                    new PrintAttributes.Builder().build());
    
        }
    

    The printJob will be execute only with SDK 19 and above