/**
* 执行网络打印
*/
public void doNetWorkPrint(String reportUrl) {
WebView printWebView = new WebView(this);
printWebView.setWebChromeClient(new WebChromeClient());
printWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
printOrCreatePdfFromWebview(view,"打印标题");
super.onPageFinished(view, url);
}
});
WebSettings webSetting = printWebView.getSettings();
webSetting.setDomStorageEnabled(true);
webSetting.setCacheMode(WebSettings.LOAD_DEFAULT);
webSetting.setDatabaseEnabled(true);
webSetting.setJavaScriptEnabled(true);
webSetting.setAllowFileAccess(true);
webSetting.setAppCacheEnabled(true);
// 允许从任何来源加载内容,即使起源是不安全的;
//webview 从Lollipop(5.0)开始 webview默认不允许混合模式,https当中不能加载http资源,如果要加载,需单独设置开启
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
webSetting.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
}
printWebView.loadUrl(reportUrl);
}
public PrintJob printOrCreatePdfFromWebview(WebView webview, String jobName) {
Context context = webview.getContext();
if (!(context instanceof Activity)) {
return null;
}
PrintDocumentAdapter printAdapter;
PrintManager printManager = (PrintManager) context.getSystemService(Context.PRINT_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
printAdapter = webview.createPrintDocumentAdapter(jobName);
} else {
printAdapter = webview.createPrintDocumentAdapter();
}
if (printManager != null) {
if (((Activity) context).isFinishing()) {
return null;
}
PrintAttributes.Builder builder = new PrintAttributes.Builder();
//设置A4纸
builder.setMediaSize(PrintAttributes.MediaSize.ISO_A4);
//设置横向
?????builder.setMediaSize(PrintAttributes.MediaSize.UNKNOWN_LANDSCAPE);
return printManager.print(jobName, printAdapter, builder.build());
}
return null;
}
|