How do I enable print functionality in Android WebView

Viewed 41

I'm opening a WebView in my app, after navigating in the website, the user arrives at a page with a button to print "Click to print" which would print the page the user is at. It works just fine in Chrome on mobile and opens PDF for printing, however, in WebView the button doesn't seem to do anything when clicked.

My question, is there a way to get that button to trigger a print job?

I tried something like this which triggers a print job just fine but not when the button is clicked and I can't access the button's JS onClick method to override in app.

private fun createWebPrintJob(webView: WebView) {
    val printManager = this@Activity
        .getSystemService(PRINT_SERVICE) as PrintManager
    val jobName = "Test Doc"
    val printAdapter = webView.createPrintDocumentAdapter(jobName)
    val printJob: PrintJob = printManager.print(
        jobName, printAdapter,
        PrintAttributes.Builder().build()
    )
    printJobs.add(printJob)
}

Any ideas on how I can get the WebView to behave same as Chrome?

1 Answers

You have to create a custom WebViewClient() class and override shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest) inside it and set a tag for example "print" for the action of the button and set if statement inside shouldOverrideUrlLoading() method.

private val mWebViewClient = object : WebViewClient() {
    override fun shouldOverrideUrlLoading(
        view: WebView?,
        request: WebResourceRequest?
    ): Boolean {
        if (request?.url.toString() == "print"){
            doPrint()
            return false
        }
    }
}

webView.webViewClient = mWebViewClient
Related