如何从WebView获取HTML内容以进行打印?

时间:2018-02-11 15:32:19

标签: java android webview native hybrid-mobile-app

我在webview中的代码如下:

setContentView(R.layout.main);
        webView = (WebView) findViewById(R.id.mainWebView);
        webView.setWebViewClient(new WebViewClient() {
             @Override
             public void onPageFinished(WebView view, String url) {
                 super.onPageFinished(view, url);
                 webView.setWebViewClient(null);
                 webView.loadUrl("javascript:window.HTMLOUT.processHTML('<div>'+document.getElementsByTagName('div')[0].innerHTML+'</div>');");
             }
        });
        webView.loadUrl("http://sample.com/");

我还有webview打印的代码如下

case R.id.Send_Button:{
                String msg = webView.getUrl().toString();
                if(msg.length()>0){
                    SendDataByte(PrinterCommand.POS_Print_Text(msg, CHINESE, 0, 0, 0, 0));
                    SendDataByte(Command.LF);
                }else{
                    Toast.makeText(Main_Activity.this, getText(R.string.empty), Toast.LENGTH_SHORT).show();
                }
            break;
        }

问题是,为什么只打印网址?而我想在http://sample.com/上打印一页?

我真的需要你的建议。谢谢

1 个答案:

答案 0 :(得分:0)

使用jsoup来获取网页内容

                      URL urlobject = new URL(url);
                        HttpURLConnection connect = (HttpURLConnection) urlobject.openConnection();
                        connect.setRequestMethod("HEAD");
                        connect.connect();
                        if(connect.getResponseCode() == HttpURLConnection.HTTP_OK){

                            org.jsoup.nodes.Document doc;
                            try {
                   // in doc variable you get the complete data of webpage

                              org.jsoup.nodes.Document doc;
                          doc = Jsoup.connect(url).get();
                                Element title = doc.body();
                                Spanned html = 
       Html.fromHtml(Html.fromHtml(title.toString()).toString()); 
        }catch (IOException e){
            dialog.dismiss();
        }
相关问题