列印 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/
中。
,然後在
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
的執行個體一次只能處理一項列印工作。
- 不含 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
物件的執行個體,供
而不需要使用這個設定檔您的應用程式可能會使用這個物件來追蹤
表示正在處理的列印工作如要監控狀態,這個方法很實用
以瞭解列印工作的完成狀態,以便完成、失敗或使用者取消作業。建立
列印架構會自動建立系統,因此不需要應用程式內通知
接收列印工作通知。
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-07-27 (世界標準時間)。
[[["容易理解","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 (世界標準時間)。"],[],[],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."]]