HTML ドキュメントの印刷
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
Android でシンプルな写真以外のコンテンツを印刷するには、テキストとグラフィックを
印刷します。Android フレームワークは、HTML を使用してドキュメントを作成し、
必要最小限のコードで出力できます
Android 4.4(API レベル 19)で、WebView
クラスは次のように更新されました。
HTML コンテンツの印刷を有効にします。このクラスを使用すると、ローカルの HTML リソースの読み込みや、
印刷ジョブを作成して Android の印刷サービスに引き渡すこともできます。
このレッスンでは、テキストとグラフィックスを含む HTML ドキュメントを、
WebView
を使用して出力します。
HTML ドキュメントを読み込む
WebView
を使用して HTML ドキュメントを印刷するには、HTML を読み込みます。
HTML ドキュメントを文字列として作成することもできます。このセクションでは、HTML のビルド方法について説明します。
出力のために WebView
に読み込んでください。
このビュー オブジェクトは、通常、アクティビティ レイアウトの一部として使用されます。ただし、アプリケーションで
WebView
を使用していない場合は、クラスのインスタンスを作成して、
特に印刷目的での使用の場合ですこのカスタム印刷ビューの主な作成手順は次のとおりです。
- 次の時間が経過したら印刷ジョブを開始する
WebViewClient
を作成する
HTML リソースが読み込まれます。
- HTML リソースを
WebView
オブジェクトに読み込みます。
次のコード例は、シンプルな WebViewClient
を作成して、作成された HTML ドキュメントをその場で読み込む方法を示しています。
Kotlin
private var mWebView: WebView? = null
private fun doWebViewPrint() {
// Create a WebView object specifically for printing
val webView = WebView(activity)
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest) = false
override fun onPageFinished(view: WebView, url: String) {
Log.i(TAG, "page finished loading $url")
createWebPrintJob(view)
mWebView = null
}
}
// Generate an HTML document on the fly:
val 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
}
Java
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;
}
注: 印刷ジョブを生成するための呼び出しが、前のセクションで作成した WebViewClient
の onPageFinished()
メソッドで発生していることを確認してください。ページが開くまで
読み込みが終了しても、印刷出力が不完全または空白になるか、完全に失敗する場合があります。
注: 上記のサンプルコードは、
印刷ジョブの前にガベージ コレクションの対象から外れるように、WebView
オブジェクトを割り当てます。
作成されます。必ず独自の実装を行ってください。それ以外の場合は、印刷プロセスで行います。
失敗する可能性があります。
ページに画像を含める場合は、画像ファイルを assets/
に配置します。
ディレクトリを作成し、アプリケーションの最初のパラメータでベース URL を
loadDataWithBaseURL()
メソッドをご覧ください。
次のコード例:
Kotlin
webView.loadDataWithBaseURL(
"file:///android_asset/images/",
htmlBody,
"text/HTML",
"UTF-8",
null
)
Java
webView.loadDataWithBaseURL("file:///android_asset/images/", htmlBody,
"text/HTML", "UTF-8", null);
また、元のウェブページを
loadDataWithBaseURL()
メソッド
次のように loadUrl()
を設定します。
Kotlin
webView.loadUrl("https://developer.android.com/about/index.html")
Java
// Print an existing web page (remember to request INTERNET permission!):
webView.loadUrl("https://developer.android.com/about/index.html");
WebView
を使用して印刷ドキュメントを作成する場合、以下の点にご注意ください。
次の制限があります。
- ページ番号などのヘッダーまたはフッターをドキュメントに追加することはできません。
- HTML ドキュメントの印刷オプションにページの印刷機能がない
例: 10 ページの HTML ドキュメントの 2 ~ 4 ページ目の印刷はサポートされていません。
WebView
のインスタンスが処理できるのは、一度に 1 つの印刷ジョブだけです。
- 横向きプロパティなどの CSS 印刷属性を含む HTML ドキュメントは、
サポートされません。
- HTML ドキュメントで JavaScript を使用して印刷をトリガーすることはできません。
注:WebView
ドキュメントが読み込まれた後にレイアウトを印刷することもできます。
よりカスタマイズされた印刷出力を作成し、コンテンツを完全に制御する場合
印刷したページに描画したら、次のレッスンに進んでください。
カスタム ドキュメントの印刷に関するレッスンをご覧ください。
印刷ジョブを作成する
WebView
を作成して HTML コンテンツを読み込んだら、
あと少しで完了です。次のステップでは
PrintManager
、プリント アダプターの作成、プリントの作成
できます。次の例は、この手順を実行する方法を示しています。
Kotlin
private fun createWebPrintJob(webView: WebView) {
// Get a PrintManager instance
(activity?.getSystemService(Context.PRINT_SERVICE) as? PrintManager)?.let { printManager ->
val jobName = "${getString(R.string.app_name)} Document"
// Get a print adapter instance
val printAdapter = webView.createPrintDocumentAdapter(jobName)
// Create a print job with name and adapter instance
printManager.print(
jobName,
printAdapter,
PrintAttributes.Builder().build()
).also { printJob ->
// Save the job object for later status checking
printJobs += printJob
}
}
}
Java
private void createWebPrintJob(WebView webView) {
// Get a PrintManager instance
PrintManager printManager = (PrintManager) getActivity()
.getSystemService(Context.PRINT_SERVICE);
String jobName = getString(R.string.app_name) + " Document";
// Get a print adapter instance
PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter(jobName);
// Create a print job with name and adapter instance
PrintJob printJob = printManager.print(jobName, printAdapter,
new PrintAttributes.Builder().build());
// Save the job object for later status checking
printJobs.add(printJob);
}
この例では、PrintJob
オブジェクトのインスタンスを保存して、
必須ではありません。アプリケーションはこのオブジェクトを使用して、
印刷ジョブが処理中ですこの方法は、Google Cloud リソースのステータスを
完了、失敗、ユーザーによるキャンセルなどが発生したときに、自動的に印刷ジョブのステータスに戻ります。作成中の
アプリ内通知は不要です。これは、印刷フレームワークが自動的に
通知が送られます。
このページのコンテンツやコードサンプルは、コンテンツ ライセンスに記載のライセンスに従います。Java および OpenJDK は Oracle および関連会社の商標または登録商標です。
最終更新日 2025-07-27 UTC。
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["必要な情報がない","missingTheInformationINeed","thumb-down"],["複雑すぎる / 手順が多すぎる","tooComplicatedTooManySteps","thumb-down"],["最新ではない","outOfDate","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["サンプル / コードに問題がある","samplesCodeIssue","thumb-down"],["その他","otherDown","thumb-down"]],["最終更新日 2025-07-27 UTC。"],[],[],null,["# Printing HTML documents\n\nPrinting out content beyond a simple photo on Android requires composing text and graphics in a\nprint document. The Android framework provides a way to use HTML to compose a document and\nprint it with a minimum of code.\n\nIn Android 4.4 (API level 19), the [WebView](/reference/android/webkit/WebView) class has been updated to\nenable printing HTML content. The class allows you to load a local HTML resource or download\na page from the web, create a print job and hand it off to Android's print services.\n\nThis lesson shows you how to quickly build an HTML document containing text and graphics and\nuse [WebView](/reference/android/webkit/WebView) to print it.\n\nLoad an HTML document\n---------------------\n\nPrinting an HTML document with [WebView](/reference/android/webkit/WebView) involves loading an HTML\nresource or building an HTML document as a string. This section describes how to build an HTML\nstring and load it into a [WebView](/reference/android/webkit/WebView) for printing.\n\nThis view object is typically used as part of an activity layout. However, if your application\nis not using a [WebView](/reference/android/webkit/WebView), you can create an instance of the class\nspecifically for printing purposes. The main steps for creating this custom print view are:\n\n1. Create a [WebViewClient](/reference/android/webkit/WebViewClient) that starts a print job after the HTML resource is loaded.\n2. Load the HTML resource into the [WebView](/reference/android/webkit/WebView) object.\n\nThe following code sample demonstrates how to create a simple [WebViewClient](/reference/android/webkit/WebViewClient) and load an HTML document created on the fly: \n\n### Kotlin\n\n```kotlin\nprivate var mWebView: WebView? = null\n\nprivate fun doWebViewPrint() {\n // Create a WebView object specifically for printing\n val webView = WebView(activity)\n webView.webViewClient = object : WebViewClient() {\n\n override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest) = false\n\n override fun onPageFinished(view: WebView, url: String) {\n Log.i(TAG, \"page finished loading $url\")\n createWebPrintJob(view)\n mWebView = null\n }\n }\n\n // Generate an HTML document on the fly:\n val htmlDocument =\n \"\u003chtml\u003e\u003cbody\u003e\u003ch1\u003eTest Content\u003c/h1\u003e\u003cp\u003eTesting, testing, testing...\u003c/p\u003e\u003c/body\u003e\u003c/html\u003e\"\n webView.loadDataWithBaseURL(null, htmlDocument, \"text/HTML\", \"UTF-8\", null)\n\n // Keep a reference to WebView object until you pass the PrintDocumentAdapter\n // to the PrintManager\n mWebView = webView\n}\n```\n\n### Java\n\n```java\nprivate WebView mWebView;\n\nprivate void doWebViewPrint() {\n // Create a WebView object specifically for printing\n WebView webView = new WebView(getActivity());\n webView.setWebViewClient(new WebViewClient() {\n\n public boolean shouldOverrideUrlLoading(WebView view, String url) {\n return false;\n }\n\n @Override\n public void onPageFinished(WebView view, String url) {\n Log.i(TAG, \"page finished loading \" + url);\n createWebPrintJob(view);\n mWebView = null;\n }\n });\n\n // Generate an HTML document on the fly:\n String htmlDocument = \"\u003chtml\u003e\u003cbody\u003e\u003ch1\u003eTest Content\u003c/h1\u003e\u003cp\u003eTesting, \" +\n \"testing, testing...\u003c/p\u003e\u003c/body\u003e\u003c/html\u003e\";\n webView.loadDataWithBaseURL(null, htmlDocument, \"text/HTML\", \"UTF-8\", null);\n\n // Keep a reference to WebView object until you pass the PrintDocumentAdapter\n // to the PrintManager\n mWebView = webView;\n}\n```\n\n\n**Note:** Make sure your call for generating a print job happens in the [onPageFinished()](/reference/android/webkit/WebViewClient#onPageFinished(android.webkit.WebView, java.lang.String)) method of the [WebViewClient](/reference/android/webkit/WebViewClient) you created in the previous section. If you don't wait until page\nloading is finished, the print output may be incomplete or blank, or may fail completely.\n\n\n**Note:** The example code above holds an instance of the\n[WebView](/reference/android/webkit/WebView) object so that is it not garbage collected before the print job\nis created. Make sure you do the same in your own implementation, otherwise the print process\nmay fail.\n\n\nIf you want to include graphics in the page, place the graphic files in the `assets/`\ndirectory of your project and specify a base URL in the first parameter of the\n[loadDataWithBaseURL()](/reference/android/webkit/WebView#loadDataWithBaseURL(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)) method, as shown in the\nfollowing code example: \n\n### Kotlin\n\n```kotlin\nwebView.loadDataWithBaseURL(\n \"file:///android_asset/images/\",\n htmlBody,\n \"text/HTML\",\n \"UTF-8\",\n null\n)\n```\n\n### Java\n\n```java\nwebView.loadDataWithBaseURL(\"file:///android_asset/images/\", htmlBody,\n \"text/HTML\", \"UTF-8\", null);\n```\n\nYou can also load a web page for printing by replacing the\n[loadDataWithBaseURL()](/reference/android/webkit/WebView#loadDataWithBaseURL(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)) method with\n[loadUrl()](/reference/android/webkit/WebView#loadUrl(java.lang.String)) as shown below. \n\n### Kotlin\n\n```kotlin\nwebView.loadUrl(\"https://developer.android.com/about/index.html\")\n```\n\n### Java\n\n```java\n// Print an existing web page (remember to request INTERNET permission!):\nwebView.loadUrl(\"https://developer.android.com/about/index.html\");\n```\n\nWhen using [WebView](/reference/android/webkit/WebView) for creating print documents, you should be aware of\nthe following limitations:\n\n- You cannot add headers or footers, including page numbers, to the document.\n- 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.\n- An instance of [WebView](/reference/android/webkit/WebView) can only process one print job at a time.\n- An HTML document containing CSS print attributes, such as landscape properties, is not supported.\n- You cannot use JavaScript in a HTML document to trigger printing.\n\n\n**Note:** The content of a [WebView](/reference/android/webkit/WebView) object that is included in\na layout can also be printed once it has loaded a document.\n\nIf you want to create a more customized print output and have complete control of the content\ndraw on the printed page, jump to the next lesson:\n[Printing a custom document](/training/printing/custom-docs) lesson.\n\nCreate a print job\n------------------\n\nAfter creating a [WebView](/reference/android/webkit/WebView) and loading your HTML content, your\napplication is almost done with its part of the printing process. The next steps are accessing\nthe [PrintManager](/reference/android/print/PrintManager), creating a print adapter, and finally, creating a print\njob. The following example illustrates how to perform these steps: \n\n### Kotlin\n\n```kotlin\nprivate fun createWebPrintJob(webView: WebView) {\n\n // Get a PrintManager instance\n (activity?.getSystemService(Context.PRINT_SERVICE) as? PrintManager)?.let { printManager -\u003e\n\n val jobName = \"${getString(R.string.app_name)} Document\"\n\n // Get a print adapter instance\n val printAdapter = webView.createPrintDocumentAdapter(jobName)\n\n // Create a print job with name and adapter instance\n printManager.print(\n jobName,\n printAdapter,\n PrintAttributes.Builder().build()\n ).also { printJob -\u003e\n\n // Save the job object for later status checking\n printJobs += printJob\n }\n }\n}\n```\n\n### Java\n\n```java\nprivate void createWebPrintJob(WebView webView) {\n\n // Get a PrintManager instance\n PrintManager printManager = (PrintManager) getActivity()\n .getSystemService(Context.PRINT_SERVICE);\n\n String jobName = getString(R.string.app_name) + \" Document\";\n\n // Get a print adapter instance\n PrintDocumentAdapter printAdapter = webView.createPrintDocumentAdapter(jobName);\n\n // Create a print job with name and adapter instance\n PrintJob printJob = printManager.print(jobName, printAdapter,\n new PrintAttributes.Builder().build());\n\n // Save the job object for later status checking\n printJobs.add(printJob);\n}\n```\n\nThis example saves an instance of the [PrintJob](/reference/android/print/PrintJob) object for use by the\napplication, which is not required. Your application may use this object to track the progress of\nthe print job as it's being processed. This approach is useful when you want to monitor the status\nof the print job in you application for completion, failure, or user cancellation. Creating an\nin-app notification is not required, because the print framework automatically creates a system\nnotification for the print job."]]