跳转到相应内容

最常访问

最近访问

navigation

Printing HTML Documents

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 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:

  1. Create a WebViewClient that starts a print job after the HTML resource is loaded.
  2. Load the HTML resource into the WebView object.

The following code sample demonstrates how to create a simple 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 onPageFinished() method of the 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 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 assets/ directory of your project and specify a base URL in the first parameter of the 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 loadDataWithBaseURL() method with 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 WebView for creating print documents, you should be aware of the following limitations:

Note: The content of a 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 WebView and loading your HTML content, your application is almost done with its part of the printing process. The next steps are accessing the 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 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.

此网站会使用 Cookie 来存储您在此网站上指定的语言和显示选项偏好设置。

获取最新的 Android Developers 资讯和提示,助您在 Google Play 上取得成功。

* 必填字段

成功!

在微信上关注 Google Developers

要以浏览此网站吗?

您请求访问的是网页,但是您为此网站设置的语言偏好为

要更改您的语言偏好设置并以浏览此网站吗?如果以后您想要更改语言偏好设置,请使用每个页面底部的语言菜单。

该类需要 或更高的 API 级别

此文档已被隐藏,因为您为该文档选择的 API 级别是 。您可以使用左侧导航栏上方的选择器来更改文档的 API 级别。

要详细了解如何根据您的应用需求指定 API 级别,请参阅支持不同平台版本

Take a short survey?
Help us improve the Android developer experience. (April 2018 — Developer Survey)