1 /* 2 * Copyright (C) 2013 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.example.android.apis.app; 18 19 import android.app.Activity; 20 import android.content.Context; 21 import android.os.Bundle; 22 import android.print.PrintManager; 23 import android.view.Menu; 24 import android.view.MenuItem; 25 import android.webkit.WebView; 26 import android.webkit.WebViewClient; 27 28 import com.example.android.apis.R; 29 30 /** 31 * This class demonstrates how to implement HTML content printing 32 * from a {@link WebView} which is shown on the screen. 33 * <p> 34 * This activity shows a simple HTML content in a {@link WebView} 35 * and allows the user to print that content via an action in the 36 * action bar. The shown {@link WebView} is doing the printing. 37 * </p> 38 * 39 * @see PrintManager 40 * @see WebView 41 */ 42 public class PrintHtmlFromScreen extends Activity { 43 44 private WebView mWebView; 45 46 private boolean mDataLoaded; 47 48 @Override onCreate(Bundle savedInstanceState)49 protected void onCreate(Bundle savedInstanceState) { 50 super.onCreate(savedInstanceState); 51 setContentView(R.layout.print_html_from_screen); 52 mWebView = (WebView) findViewById(R.id.web_view); 53 54 // Important: Only enable the print option after the page is loaded. 55 mWebView.setWebViewClient(new WebViewClient() { 56 @Override 57 public void onPageFinished(WebView view, String url) { 58 // Data loaded, so now we want to show the print option. 59 mDataLoaded = true; 60 invalidateOptionsMenu(); 61 } 62 }); 63 64 // Load an HTML page. 65 mWebView.loadUrl("file:///android_res/raw/motogp_stats.html"); 66 } 67 68 @Override onCreateOptionsMenu(Menu menu)69 public boolean onCreateOptionsMenu(Menu menu) { 70 super.onCreateOptionsMenu(menu); 71 if (mDataLoaded) { 72 getMenuInflater().inflate(R.menu.print_custom_content, menu); 73 } 74 return true; 75 } 76 77 @Override onOptionsItemSelected(MenuItem item)78 public boolean onOptionsItemSelected(MenuItem item) { 79 if (item.getItemId() == R.id.menu_print) { 80 print(); 81 return true; 82 } 83 return super.onOptionsItemSelected(item); 84 } 85 print()86 private void print() { 87 // Get the print manager. 88 PrintManager printManager = (PrintManager) getSystemService( 89 Context.PRINT_SERVICE); 90 // Pass in the ViewView's document adapter. 91 printManager.print("MotoGP stats", mWebView.createPrintDocumentAdapter(), null); 92 } 93 } 94