page.title=Printing HTML Documents parent.title=Printing Content parent.link=index.html trainingnavtop=true next.title=Printing Custom Documents next.link=custom-docs.html @jd:body

This lesson teaches you to

  1. Load an HTML Document
  2. Create a Print Job

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 {@link android.webkit.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 {@link android.webkit.WebView} to print it.

Load an HTML Document

Printing an HTML document with {@link android.webkit.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 {@link android.webkit.WebView} for printing.

This view object is typically used as part of an activity layout. However, if your application is not using a {@link android.webkit.WebView}, you can create an instance of the class specifically for printing purposes. The main steps for creating this custom print view are:

  1. Create a {@link android.webkit.WebViewClient} that starts a print job after the HTML resource is loaded.
  2. Load the HTML resource into the {@link android.webkit.WebView} object.

The following code sample demonstrates how to create a simple {@link android.webkit.WebViewClient} and load an HTML document created on the fly:

private WebView mWebView;

private void doWebViewPrint() {
    // Create a WebView object specifically for printing
    WebView webView = new WebView(getActivity());
    webView.setWebViewClient(new WebViewClient() {

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

            @Override
            public void onPageFinished(WebView view, String url) {
                Log.i(TAG, "page finished loading " + url);
                createWebPrintJob(view);
                mWebView = null;
            }
    });

    // Generate an HTML document on the fly:
    String htmlDocument = "<html><body><h1>Test Content</h1><p>Testing, " +
            "testing, testing...</p></body></html>";
    webView.loadDataWithBaseURL(null, htmlDocument, "text/HTML", "UTF-8", null);

    // Keep a reference to WebView object until you pass the PrintDocumentAdapter
    // to the PrintManager
    mWebView = webView;
}

Note: Make sure your call for generating a print job happens in the {@link android.webkit.WebViewClient#onPageFinished onPageFinished()} method of the {@link android.webkit.WebViewClient} you created in the previous section. If you don't wait until page loading is finished, the print output may be incomplete or blank, or may fail completely.

Note: The example code above holds an instance of the {@link android.webkit.WebView} object so that is it not garbage collected before the print job is created. Make sure you do the same in your own implementation, otherwise the print process may fail.

If you want to include graphics in the page, place the graphic files in the {@code assets/} directory of your project and specify a base URL in the first parameter of the {@link android.webkit.WebView#loadDataWithBaseURL loadDataWithBaseURL()} method, as shown in the following code example:

webView.loadDataWithBaseURL("file:///android_asset/images/", htmlBody,
        "text/HTML", "UTF-8", null);

You can also load a web page for printing by replacing the {@link android.webkit.WebView#loadDataWithBaseURL loadDataWithBaseURL()} method with {@link android.webkit.WebView#loadUrl loadUrl()} as shown below.

// Print an existing web page (remember to request INTERNET permission!):
webView.loadUrl("http://developer.android.com/about/index.html");

When using {@link android.webkit.WebView} for creating print documents, you should be aware of the following limitations:

Note: The content of a {@link android.webkit.WebView} object that is included in a layout can also be printed once it has loaded a document.

If you want to create a more customized print output and have complete control of the content draw on the printed page, jump to the next lesson: Printing a Custom Document lesson.

After creating a {@link android.webkit.WebView} and loading your HTML content, your application is almost done with its part of the printing process. The next steps are accessing the {@link android.print.PrintManager}, creating a print adapter, and finally, creating a print job. The following example illustrates how to perform these steps:

private void createWebPrintJob(WebView webView) {

    // Get a PrintManager instance
    PrintManager printManager = (PrintManager) getActivity()
            .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";
    PrintJob printJob = printManager.print(jobName, printAdapter,
            new PrintAttributes.Builder().build());

    // Save the job object for later status checking
    mPrintJobs.add(printJob);
}

This example saves an instance of the {@link android.print.PrintJob} object for use by the application, which is not required. Your application may use this object to track the progress of the print job as it's being processed. This approach is useful when you want to monitor the status of the print job in you application for completion, failure, or user cancellation. Creating an in-app notification is not required, because the print framework automatically creates a system notification for the print job.