Printing out content beyond a simple photo on Android requires composing text and graphics in a print document. The Android framework provides a way to use HTML to compose a document and print it with a minimum of code.
In Android 4.4 (API level 19), the WebView class has been updated to
enable printing HTML content. The class allows you to load a local HTML resource or download
a page from the web, create a print job and hand it off to Android's print services.
This lesson shows you how to quickly build an HTML document containing text and graphics and
use WebView to print it.
Load an HTML document
Printing an HTML document with WebView involves loading an HTML
resource or building an HTML document as a string. This section describes how to build an HTML
string and load it into a WebView for printing.
This view object is typically used as part of an activity layout. However, if your application
is not using a WebView, you can create an instance of the class
specifically for printing purposes. The main steps for creating this custom print view are:
- Create a
WebViewClientthat starts a print job after the HTML resource is loaded. - Load the HTML resource into the
WebViewobject.
The following code sample demonstrates how to create a simple WebViewClient and load an HTML document created on the fly:
Kotlin
private var mWebView: WebView? = null private fun doWebViewPrint() { // Create a WebView object specifically for printing val webView = WebView(activity) webView.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest) = false override fun onPageFinished(view: