An Android Studio HTML and Web Printing Example

As outlined in the previous chapter, entitled “Printing with the Android Printing Framework”, the Android Printing framework can print both web pages and dynamically created HTML content. While there is much similarity between these two approaches to printing, there are also some subtle differences that need to be considered. This chapter will work through the creation of two example applications to bring some clarity to these two printing options.

Creating the HTML Printing Example Application

Select the New Project option from the welcome screen and, within the resulting new project dialog, choose the Empty Views Activity template before clicking on the Next button.

Enter HTMLPrint into the Name field and specify com.ebookfrenzy.htmlprint as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language menu to Kotlin.

Printing Dynamic HTML Content

The first stage of this tutorial is to add code to the project to create some HTML content and send it to the Printing framework as a print job.

Begin by locating the MainActivity.kt file (located in the Project tool window under app -> kotlin+java -> com .ebookfrenzy.htmlprint) and loading it into the editing panel. Once loaded, modify the code so that it reads as outlined in the following listing:

 

You are reading a sample chapter from Android Studio Giraffe Essentials – Kotlin Edition.

Buy the full book now in eBook (PDF) or Print format.

The full book contains 94 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

package com.ebookfrenzy.htmlprint
 
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.print.PrintAttributes
import android.print.PrintManager
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.webkit.WebViewClient
import android.content.Context
 
class MainActivity : AppCompatActivity() {
 
    private var myWebView: WebView? = null
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_html_print)
 
        printWebView()
    }
 
    private fun printWebView() {
 
        val webView = WebView(this)
        webView.webViewClient = object : WebViewClient() {
 
            override fun shouldOverrideUrlLoading(view: WebView,
                                request: WebResourceRequest): Boolean {
                return false
            }
 
            override fun onPageFinished(view: WebView, url: String) {
                createWebPrintJob(view)
                myWebView = null
            }
        }
 
        val htmlDocument = "<html><body><h1>Android Print Test</h1><p>" + 
                            "This is some sample content.</p></body></html>"
 
        webView.loadDataWithBaseURL(null, htmlDocument,
                "text/HTML", "UTF-8", null)
 
        myWebView = webView
    }
}Code language: Kotlin (kotlin)

The code changes begin by declaring a variable named myWebView in which will be stored a reference to the WebView instance used for the printing operation. Within the printWebView() method, an instance of the WebView class is created to which a WebViewClient instance is assigned.

The WebViewClient assigned to the web view object is configured to indicate that loading the HTML content is to be handled by the WebView instance (by returning false from the shouldOverrideUrlLoading() method). More importantly, an onPageFinished() handler method is declared and implemented to call the createWebPrintJob() method. The onPageFinished() method will be called automatically when all HTML content has been loaded into the web view. As outlined in the previous chapter, this step is necessary when printing dynamically created HTML content to ensure that the print job is only started once the content has fully loaded into the WebView.

Next, a String object is created containing some HTML to serve as the content and subsequently loaded into the web view. Once the HTML is loaded, the onPageFinished() callback method will trigger. Finally, the method stores a reference to the web view object in the previously declared myWebView variable. Without this vital step, there is a significant risk that the Java runtime system will assume that the application no longer needs the web view object and will discard it to free up memory resulting in the print job terminating before completion. All that remains in this example is to implement the createWebPrintJob() method, which is currently configured to be called by the onPageFinished() callback method. Remaining within the MainActivity.kt file, therefore, implement this method so that it reads as follows:

private fun createWebPrintJob(webView: WebView) {
 
    val printManager = this
            .getSystemService(Context.PRINT_SERVICE) as PrintManager
 
    val printAdapter = webView.createPrintDocumentAdapter("MyDocument")
 
    val jobName = getString(R.string.app_name) + " Print Test"
 
    printManager.print(jobName, printAdapter,
            PrintAttributes.Builder().build())
}Code language: Kotlin (kotlin)

This method obtains a reference to the PrintManager service and instructs the web view instance to create a print adapter. A new string is created to store the name of the print job (in this case, based on the name of the application and the word “Print Test”).

Finally, the print job is started by calling the print() method of the print manager, passing through the job name, print adapter, and a set of default print attributes.

 

You are reading a sample chapter from Android Studio Giraffe Essentials – Kotlin Edition.

Buy the full book now in eBook (PDF) or Print format.

The full book contains 94 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Compile and run the application on a device or emulator running Android 5.0 or later. Once launched, the standard Android printing page should appear as illustrated in Figure 81-1.

Figure 81-1

Print to a physical printer if you have one configured, save to Google Drive, or select the option to save to a PDF file. Once the print job has been initiated, check the generated output on your chosen destination. Note that the system will request a name and location for the PDF file when using the Save to PDF option. The Downloads folder makes a good option, the contents of which can be viewed by selecting the Downloads icon (renamed Files on Android 8) located amongst the other app icons on the device

Creating the Web Page Printing Example

The second example application created in this chapter will provide the user an Overflow menu option to print the web page currently displayed within a WebView instance.

Select the New Project option from the welcome screen and, within the resulting new project dialog, choose the Basic Views Activity template before clicking on the Next button.

Enter WebPrint into the Name field and specify com.ebookfrenzy.webprint as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language menu to Kotlin.

 

You are reading a sample chapter from Android Studio Giraffe Essentials – Kotlin Edition.

Buy the full book now in eBook (PDF) or Print format.

The full book contains 94 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

Removing the Floating Action Button

Selecting the Basic Views Activity template provided a context menu and a floating action button. Since the app does not require the floating action button, it can be removed before proceeding. Load the activity_main.xml layout file into the Layout Editor, select the floating action button, and tap the keyboard Delete key to remove the object from the layout. Edit the MainActivity.kt file and remove the floating action button code from the onCreate method as follows:

override fun onCreate(savedInstanceState: Bundle?) {
.
.
    // binding.fab.setOnClickListener { view ->
    //    Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
    //        .setAction("Action", null).show()
    //}
}Code language: JavaScript (javascript)

Removing Navigation Features

As A Guide to the Android Studio Layout Editor Tool outlines, the Basic Views Activity template contains multiple fragments and buttons to navigate from one fragment to the other. These features are unnecessary for this tutorial and will cause problems later if not removed. Before moving ahead with the tutorial, modify the project as follows:

  • Within the Project tool window, navigate to and double-click on the app -> res -> navigation -> nav_graph.xml file to load it into the navigation editor.
  • Within the editor, select the SecondFragment entry in the graph panel and tap the keyboard delete key to remove it from the graph.
  • Locate and delete the SecondFragment.kt (app -> kotlin+java -> <package name> -> SecondFragment) and fragment_second.xml (app -> res -> layout -> fragment_second.xml) files.
  • Locate the FirstFragment.kt file, double-click on it to load it into the editor, and remove the code from the onViewCreated() method so that it reads as follows:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
 
    // binding.buttonFirst.setOnClickListener {
    //     findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
    // }
}Code language: JavaScript (javascript)
  • Edit the MainActivity.kt file and remove the following navigation code:
.
.
// private lateinit var appBarConfiguration: AppBarConfiguration
.
.
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
.
.
    // val navController = findNavController(R.id.nav_host_fragment_content_main)
    // appBarConfiguration = AppBarConfiguration(navController.graph)
    // setupActionBarWithNavController(navController, appBarConfiguration)
}
.
.
// override fun onSupportNavigateUp(): Boolean {
// 
//     val navController = findNavController(R.id.nav_host_fragment_content_main)
//     return navController.navigateUp(appBarConfiguration)
//             || super.onSupportNavigateUp()
//}Code language: JavaScript (javascript)

Designing the User Interface Layout

Load the content_main.xml layout resource file into the Layout Editor tool if it has not already been loaded and, in Design mode, select and delete the nav_host_fragment_content_main object. From the Widgets section of the palette, drag and drop a WebView object onto the center of the device screen layout. Click the Infer constraints toolbar button and, using the Attributes tool window, change the layout_width and layout_height properties of the WebView to match constraint so that it fills the entire layout canvas, as outlined in Figure 81-2 below.

Select the newly added WebView instance and change the ID of the view to myWebView.

Before proceeding to the next step of this tutorial, an additional permission must be added to the project to enable the WebView object to access the Internet and download a web page for printing. Add this permission by locating the AndroidManifest.xml file in the Project tool window and double-clicking on it to load it into the editing panel. Once loaded, edit the XML content to add the appropriate permission line, as shown in the following listing:

 

You are reading a sample chapter from Android Studio Giraffe Essentials – Kotlin Edition.

Buy the full book now in eBook (PDF) or Print format.

The full book contains 94 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.ebookfrenzy.webprint" >
 
    <uses-permission android:name="android.permission.INTERNET" />
             
    <application
        android:allowBackup="true"
.
.
</manifest>Code language: HTML, XML (xml)
Figure 81-2

Accessing the WebView from the Main Activity

As with the project in the chapter entitled An Android Studio RecyclerView Tutorial we need to be able to use view binding to access a component (in this case myWebView) contained in the content_main.xml file from within the MainActivity class. To access views within the content_main.xml file, we again need to assign it an id at the point it is included. Edit the activity_main.xml file and modify the include element so that it reads as follows:

.
.
   <include
        android:id="@+id/contentMain"
        layout="@layout/content_main" />
.
.Code language: HTML, XML (xml)

Loading the Web Page into the WebView

Before the web page can be printed, it must loaded into the WebView instance. For this tutorial, this will be performed by a call to the loadUrl() method of the WebView instance, which will be placed in a method named configureWebView() and called from within the onStart() method of the MainActivity class. Edit the MainActivity.kt file, therefore, and modify it as follows:

package com.ebookfrenzy.webprint
.
.
import android.webkit.WebView
import android.webkit.WebViewClient
import android.webkit.WebResourceRequest
import android.content.Context
 
class MainActivity : AppCompatActivity() {
.
.
   override fun onStart() {
        super.onStart()
        configureWebView()
    }
 
    private fun configureWebView() {
 
        binding.contentMain.myWebView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(
                    view: WebView, request: WebResourceRequest): Boolean {
                return super.shouldOverrideUrlLoading(
                        view, request)
            }
        }
        binding.contentMain.myWebView.loadUrl(
                "https://www.answertopia.com") 
    }
.
.
}Code language: Kotlin (kotlin)

Adding the Print Menu Option

The option to print the web page will now be added to the Overflow menu. The first requirement is a string resource to label the menu option. Within the Project tool window, locate the app -> res -> values -> strings.xml file, double-click on it to load it into the editor, and modify it to add a new string resource:

<resources>
    <string name="app_name">WebPrint</string>
    <string name="action_settings">Settings</string>
    <string name="print_string">Print</string>
.
.
</resources>Code language: HTML, XML (xml)

Next, load the app -> res -> menu -> menu_main.xml file into the menu editor, switch to Code mode, and replace the Settings menu option with the print option:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.ebookfrenzy.webprint.MainActivity" >
    <item
         android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never" />
 
    <item
        android:id="@+id/action_print"
        android:orderInCategory="100"
        app:showAsAction="never"         
        android:title="@string/print_string"/>
</menu>Code language: HTML, XML (xml)

All that remains in terms of configuring the menu option is to modify the onOptionsItemSelected() handler method within the MainActivity.kt file:

 

You are reading a sample chapter from Android Studio Giraffe Essentials – Kotlin Edition.

Buy the full book now in eBook (PDF) or Print format.

The full book contains 94 chapters and over 830 pages of in-depth information.

Learn more.

Preview  Buy eBook  Buy Print

 

override fun onOptionsItemSelected(item: MenuItem): Boolean {
 
    if (item.itemId == R.id.action_print) {
        createWebPrintJob(binding.contentMain.myWebView)
    }
    return super.onOptionsItemSelected(item)
}Code language: Kotlin (kotlin)

With the onOptionsItemSelected() method implemented, the activity will call a method named createWebPrintJob() when the print menu option is selected from the overflow menu. The implementation of this method is identical to that used in the previous HTMLPrint project and may now be added to the MainActivity.kt file such that it reads as follows:

.
.
import android.print.PrintAttributes
import android.print.PrintManager
.
.
class MainActivity : AppCompatActivity() {
.
.
   private fun createWebPrintJob(webView: WebView?) {
 
        val printManager = this
                .getSystemService(Context.PRINT_SERVICE) as PrintManager
 
        val printAdapter = webView?.createPrintDocumentAdapter("MyDocument")
 
        val jobName = getString(R.string.app_name) + " Print Test"
 
        printAdapter?.let {
            printManager.print(
                jobName, it,
                PrintAttributes.Builder().build()
            )
        }
    }
.
.
}Code language: Kotlin (kotlin)

With the code changes complete, run the application on a physical Android device or emulator. Once successfully launched, the WebView should be visible with the designated web page loaded. Once the page has loaded, select the Print option from the Overflow menu and use the resulting print panel to print the web page to a suitable destination.

Summary

The Android Printing framework includes extensions to the WebView class that allow printing HTML-based content from within an Android application. This content can be HTML created dynamically within the application at runtime or a pre-existing web page loaded into a WebView instance. In the case of dynamically created HTML, it is important to use a WebViewClient instance to ensure that printing does not start until the HTML has been fully loaded into the WebView.