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

<div id="tb-wrapper">
<div id="tb">

<h2>This lesson teaches you to</h2>
<ol>
  <li><a href="#load-html">Load an HTML Document</a></li>
  <li><a href="#print-job">Create a Print Job</a></li>
</ol>

</div>
</div>

<p>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.</p>

<p>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.</p>

<p>This lesson shows you how to quickly build an HTML document containing text and graphics and
use {@link android.webkit.WebView} to print it.</p>


<h2 id="load-html">Load an HTML Document</h2>

<p>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.</p>

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

<ol>
  <li>Create a {@link android.webkit.WebViewClient} that starts a print job after
    the HTML resource is loaded.</li>
  <li>Load the HTML resource into the {@link android.webkit.WebView} object.</li>
</ol>

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

<pre>
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;
            }

            &#64;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 = "&lt;html&gt;&lt;body&gt;&lt;h1&gt;Test Content&lt;/h1&gt;&lt;p&gt;Testing, " +
            "testing, testing...&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;";
    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;
}
</pre>

<p class="note">
  <strong>Note:</strong> 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.
</p>

<p class="note">
  <strong>Note:</strong> 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.
</p>

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

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

<p>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.</p>

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

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

<ul>
  <li>You cannot add headers or footers, including page numbers, to the document.</li>
  <li>The printing options for the HTML document do not include the ability to print page
    ranges, for example: Printing page 2 to 4 of a 10 page HTML document is not supported.</li>
  <li>An instance of {@link android.webkit.WebView} can only process one print job at a time.</li>
  <li>An HTML document containing CSS print attributes, such as landscape properties, is not
    supported.</li>
  <li>You cannot use JavaScript in a HTML document to trigger printing.</li>
</ul>

<p class="note">
  <strong>Note:</strong> 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.
</p>

<p>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:
  <a href="custom-docs.html">Printing a Custom Document</a> lesson.</p>


<h2 id="print-job">Create a Print Job</h2>

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

<pre>
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);
}
</pre>

<p>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.</p>