来自here的以下示例代码在默认浏览器" Internet"和" Chrome" Galaxy Tab S2上的浏览器。
<!DOCTYPE html>
<html>
<body>
<p>Click the button to print the current page.</p>
<button onclick="myFunction()">Print this page</button>
<script>
function myFunction() {
window.print();
}
</script>
</body>
</html>
但是,当在WebView中托管时,单击&#34时不会发生任何事情;打印此页&#34;
我的观点XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.company.MainActivity"
tools:showIn="@layout/activity_main">
<WebView
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
MainActivity.Java具有以下内容:
@Override
protected void onCreate(Bundle savedInstanceState) {
WebViewClient mWebClient = new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
};
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(mWebClient);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setGeolocationEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.loadUrl("https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_print");
}
WebView开发人员文档here明确地调出:
您无法在HTML文档中使用JavaScript来触发打印。
如何托管网页并允许JavaScript打印工作。
替代方案我已经想过但是还没有找到实施的方法:
到目前为止,为了解决这个限制,我已经添加了&#34; Print&#34;按钮到我的应用程序并运行我自己的打印代码。它工作正常,但令人困惑的用户体验为&#34; Print&#34;网页中的按钮什么都不做。
答案 0 :(得分:1)
也许这会回答您的问题: https://bugs.chromium.org/p/chromium/issues/detail?id=322303
这是Android WebView团队的答案:
嗨,
我们(Android WebView团队)正计划将此API移植到Android Q (也可以通过支持lib来降低版本,但可以通过TBD)。我们想 了解它的可能用例。
该API将是阻塞回调,因为我们想冻结 DOM /布局树用于打印渲染,这与以下行为相同 Chrome。
一旦有了回调,我们可以想象得到一个 | PrintDocumentAdapter |从WebView#getPrintDocumentAdapter()中 回调,应用程序可以1)使用| PrintDocumentAdapter |与 | PrintManager |让用户选择打印设置或2)使用它来 直接生成PDF文件。我们可能想在什么时候解锁 调用PrintDocumentAdapter#onFinish()。
此回调仅在加载内容时受益 您无法控制WebView,该应用仍需要支持 打印功能。否则,应用程序可以使用| PrintDocumentAdapter | 直接。
我们还想知道您是否认为iframe中的window.print() 是否仅打印该iframe中的内容)对您而言是否重要。 支持这一点是暂时的,因为没有明显的方法可以 getPrintDocumentAdapter()知道当前window.print()来自 主框架或iframe。
问题,想法?请提供您的反馈,谢谢!