有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我在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;
        }

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

我真的需要你的建议。多谢各位


共 (1) 个答案

  1. # 1 楼答案

    使用需要使用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();
            }