简单的答案是使用 webview。
在你的 xml 文件中包含一个 webview
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<WebView
android:id="@+id/myWebView"
android:layout_alignParentLeft="true"
android:layout_below="@+id/print_button"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:text="Print"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="@+id/print_button" />
</RelativeLayout>
您可以在您的 java 类中为 webview 设置 html 代码。
String html = "<html><body>Hello, World!</body></html>";
String mime = "text/html";
String encoding = "utf-8";
final WebView myWebView = (WebView)this.findViewById(R.id.myWebView);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadDataWithBaseURL(null, html, mime, encoding, null);
Button printButton = (Button)findViewById(R.id.print_button);
printButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
createWebPrintJob(myWebView);
}
});
并使用以下方法进行打印工作
private void createWebPrintJob(WebView webView) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
PrintManager printManager = (PrintManager) this
.getSystemService(Context.PRINT_SERVICE);
PrintDocumentAdapter printAdapter =
null;
printAdapter = webView.createPrintDocumentAdapter("MyDocument");
String jobName = getString(R.string.app_name) + " Print Test";
printManager.print(jobName, printAdapter,
new PrintAttributes.Builder().build());
}
else{
Toast.makeText(MainActivity.this, "Print job has been canceled! ", Toast.LENGTH_SHORT).show();
}
}
注意:上述方法仅适用于 Lollipop 或更高版本的潜水。无论如何,如果需要,您可以将 web 视图保存为位图。
代码已经过测试并且可以工作。希望对你有帮助