简体   繁体   中英

How to get HTML Content from WebView for print?

I have code in webview as follows :

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/");

and I also have the code for the webview print as follows

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

The question is, why is it printed just url only? whereas I want to print a page on http://sample.com/ ?

I really need your advice. Thank you

Use need to use jsoup for getting webpage content

                      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();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM