An Android HTML and Web Content Printing Example

From Techotopia
Revision as of 21:08, 1 February 2016 by Neil (Talk | contribs) (Text replacement - "<google>BUY_ANDROID</google>" to "<htmlet>androidstudio</htmlet>")

Jump to: navigation, search
PreviousTable of ContentsNext
Printing with the Android Printing FrameworkAn Android Custom Document Printing Tutorial


You are currently reading the Android Studio 1.x - Android 5 Edition of this book.

Purchase the fully updated Android Studio Hedgehog Edition of this publication in eBook ($32.99) or Print ($49.99) format

Android Studio Hedgehog Essentials - Java Edition Print and eBook (PDF) editions contain 87 chapters and over 800 pages
Buy Print Preview Book


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


Contents


Creating the HTML Printing Example Application

Begin this example by launching the Eclipse environment and selecting the File -> New -> Android Application Project… menu option. Name the application and project HTMLPrint, enter a suitable package name (or com.example.htmlprint if you do not yet have a domain name) and select API 19 or later for the SDK settings. As with previous examples, request the creation of a blank activity and the use of the default launcher icons. On the New Blank Activity screen of the New Android Application wizard, set the Activity Name to HTMLPrintActivity, the Layout Name to activity_html_print and the Fragment Layout name to fragment_html_print.

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 in the form of a print job.

Begin by locating the HTMLPrintActivity.java file and loading it into the editing panel. Once loaded, modify the code so that it reads as outlined in the following listing:

package com.example.htmlprint;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import android.content.Context;

public class HTMLPrintActivity extends Activity {

	private WebView myWebView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_html_print);

	if (savedInstanceState == null) {
			getSupportFragmentManager().beginTransaction()
				.add(R.id.container, 
				new PlaceholderFragment()).commit();
		}
		
	    	WebView webView = new WebView(this);
	    	webView.setWebViewClient(new WebViewClient() {

	           public boolean shouldOverrideUrlLoading(WebView view, 
                              String url) 
		   {
	                return false;     
	           }

	           @Override
	           public void onPageFinished(WebView view, String url) 
		   {
	                createWebPrintJob(view);
	                myWebView = null;
	           }
	    });

	    String 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;
	}
.
.
.
}

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 onCreate() method, an instance of the WebView class is created to which a WebViewClient instance is then assigned.

The WebViewClient assigned to the web view object is configured to indicate that loading of 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 a method named createWebPrintJob(). The onPageFinished() method will be called automatically when all of the 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 not started until 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 HTMLPrintActivity.java file, therefore, implement this method as follows:

private void createWebPrintJob(WebView webView) {

	PrintManager printManager = (PrintManager) this
		  .getSystemService(Context.PRINT_SERVICE);

	PrintDocumentAdapter printAdapter = 
	         webView.createPrintDocumentAdapter();

	String jobName = getString(R.string.app_name) + " Print Test";

	printManager.print(jobName, printAdapter,
		   new PrintAttributes.Builder().build());
}

This method obtains a reference to the PrintManager service and instructs the web view instance to create a print adaptor. 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 adaptor and a set of default print attributes.

Compile and run the application on a device running Android 4.4 or later. Once launched, the printing panel should appear as illustrated in Figure 50-1.


The Android Printing Framework Print dialog

Figure 50-1


Print to a physical printer if you have one configured, save to Google Drive or, alternatively, 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 when using the Save to PDF option, the system will request a name and location for the PDF file. The Downloads folder makes a good option, the contents of which can be viewed by selecting the Downloads icon located amongst the other app icons on the device. Figure 50-2, for example, shows the PDF output generated by the Save to PDF option viewed on an Android device:


PDF output from the Android Printing framework

Figure 50-2


Creating the Web Page Printing Example

The second example application to be created in this chapter will provide the user with an Overflow menu option to print the web page currently displayed within a WebView instance. Within the Eclipse environment, begin this example by selecting the File -> New -> Android Application Project… menu option. Name the application and project WebPrint, enter a suitable package name (or com.example.webprint if you do not yet have a domain name) and select API 19 or later for the SDK settings. As with the HTML example, request the creation of a blank activity and the use of the default launcher icons. On the New Blank Activity screen of the New Android Application wizard, set the Activity Name to WebPrintActivity and the Layout Name and Fragment Layout Name to activity_web_print and fragment_web_print respectively.

Designing the User Interface Layout

Load the fragment_web_print.xml layout resource file into the Graphical Layout editor if it has not already been loaded and select and delete the “Hello World!” TextView object.

Switch to the XML view by clicking on the fragment_web_print.xml tab located along the lower edge of the editor panel and remove the padding properties from the file so that the WebView will extend to the edges of the display when added to the layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".WebPrintActivity" >

</RelativeLayout>

Switch back to the graphical layout view and, from the Composite section of the palette, drag and drop a WebView object so that it fills the entire layout canvas as outlined in Figure 50-3:


A WebView object added to the Android web printing example UI

Figure 50-3


Right-click on the newly added WebView instance, select the Edit ID… menu option and change the name of the view to myWebView before clicking on OK to commit the change.

Before proceeding to the next step of this tutorial, an additional permission needs to 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 Explorer panel and double clicking on it to load it into the editing panel. Once loaded, directly edit the XML content by clicking on the AndroidManifest.xml tab located along the bottom edge of the manifest editor panel. Within the XML, add the appropriate permission line as shown in the following listing:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.webprint"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-permission android:name="android.permission.INTERNET" />
    
    <uses-sdk
        android:minSdkVersion="19"
        android:targetSdkVersion="19" />
.
.
.
</manifest>

Save both layout and manifest files before proceeding.

You are currently reading the Android Studio 1.x - Android 5 Edition of this book.

Purchase the fully updated Android Studio Hedgehog Edition of this publication in eBook ($32.99) or Print ($49.99) format

Android Studio Hedgehog Essentials - Java Edition Print and eBook (PDF) editions contain 87 chapters and over 800 pages
Buy Print Preview Book

Loading the Web Page into the WebView

Before the web page can be printed it needs to be loaded into the WebView instance. For the purposes of this tutorial, this will be performed by a call to the loadUrl() method of the WebView instance which will be placed in the onStart() method of the WebPrintActivity class. Edit the WebPrintActivity.java file, therefore, and modify it as follows:

package com.example.webprint;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.webkit.WebView;

public class WebPrintActivity extends Activity {

	private WebView myWebView;
	
	@Override
	protected void onStart() {
		super.onStart();
		
		myWebView = (WebView) findViewById(R.id.myWebView);
		
		myWebView.loadUrl(
                     "http://developer.android.com/google/index.html");

	}
.
.
}

Adding the Print Menu Option

The option to print the web page will now be added to the Overflow menu using the techniques outlined in the chapter entitled Creating and Managing Overflow Menus on Android.

The first requirement is a string resource with which to label the menu option. Within the Project Explorer panel, locate the res/values/strings.xml file and double click on it to load it into the resource editor. Display the XML view by clicking on the strings.xml tab and modify it to add a new string resource:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">WebPrint</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="print_string">Print</string>
</resources>

Next, locate and edit the res/menu/web_print.xml file and replace the Settings menu option with the print option:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    
    <item
        android:id="@+id/action_print"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="@string/print_string"/>
</menu>

Once the changes have been made, save and close the resource files before continuing. All that remains in terms of configuring the menu option is to implement the onOptionsItemSelected() handler method within the WebPrintActivity.java file:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
	switch (item.getItemId()) {
           case R.id.action_print:
        	createWebPrintJob(myWebView);
        	return true;
        default:
            return super.onOptionsItemSelected(item);
	}
}

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 WebPrintActivity.java file such that it reads as follows:

package com.example.webprint;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.webkit.WebView;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.print.PrintManager;
import android.content.Context;

public class WebPrintActivity extends Activity {

	private WebView myWebView;
.
.
.
	private void createWebPrintJob(WebView webView) {

		PrintManager printManager = (PrintManager) this
			  .getSystemService(Context.PRINT_SERVICE);

		PrintDocumentAdapter printAdapter = 
		         webView.createPrintDocumentAdapter();

		String jobName = getString(R.string.app_name) + 
                            " Print Test";

		printManager.print(jobName, printAdapter,
			   new PrintAttributes.Builder().build());
	}
.
.
}

With the code changes complete, run the application on a physical Android device running Android version 4.4 or later. 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 (Figure 50-4) and use the resulting print panel to print the web page to a suitable destination.


The Print menu option added to the Overflow menu of an Android app

Figure 50-4


Summary

The Android Printing framework includes extensions to the WebView class that make it possible to print HTML based content from within an Android application. This content can be in the form of 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.


You are currently reading the Android Studio 1.x - Android 5 Edition of this book.

Purchase the fully updated Android Studio Hedgehog Edition of this publication in eBook ($32.99) or Print ($49.99) format

Android Studio Hedgehog Essentials - Java Edition Print and eBook (PDF) editions contain 87 chapters and over 800 pages
Buy Print Preview Book



PreviousTable of ContentsNext
Printing with the Android Printing FrameworkAn Android Custom Document Printing Tutorial