2013-01-11 14 views
18

JAVA FXコントロールを使用してスイングアプリケーションに取り組んでいます。私のアプリケーションでは、webviewに表示されたhtmlページをプリントアウトする必要があります。私がしようとしているのは、HtmlDocuementの助けを借りて文字列にwebviewのhtmlコンテンツを読み込むことです。ウェブビューからhtmlファイルの内容をロードするためにjavafxを使用してwebviewから内容を取得します

、私は次のコードを使用していますが、そのは動作していない:

try 
{ 
    String str=webview1.getEngine().getDocment().Body().outerHtml(); 
} 
catch(Exception ex) 
{ 
} 

答えて

18

WebEngine.getDocument戻りorg.w3c.dom.Document、あなたのコードから判断期待しないでJavaScriptの文書を。

残念ながら、org.w3c.dom.Documentを印刷するにはかなりのコードが必要です。 What is the shortest way to pretty print a org.w3c.dom.Document to stdout?から解決策を試すことができます(下のコードを参照)。

Documentで作業する前に、ドキュメントが読み込まれるまで待つ必要があることに注意してください。 LoadWorkerが、ここで使用されている理由はここにある:

public void start(Stage primaryStage) { 
    WebView webview = new WebView(); 
    final WebEngine webengine = webview.getEngine(); 
    webengine.getLoadWorker().stateProperty().addListener(
      new ChangeListener<State>() { 
       public void changed(ObservableValue ov, State oldState, State newState) { 
        if (newState == Worker.State.SUCCEEDED) { 
         Document doc = webengine.getDocument(); 
         try { 
          Transformer transformer = TransformerFactory.newInstance().newTransformer(); 
          transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); 
          transformer.setOutputProperty(OutputKeys.METHOD, "xml"); 
          transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 
          transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); 
          transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); 

          transformer.transform(new DOMSource(doc), 
            new StreamResult(new OutputStreamWriter(System.out, "UTF-8"))); 
         } catch (Exception ex) { 
          ex.printStackTrace(); 
         } 
        } 
       } 
      }); 
    webengine.load("http://stackoverflow.com"); 
    primaryStage.setScene(new Scene(webview, 800, 800)); 
    primaryStage.show(); 
} 
+0

サイトはHTML EXエラーがある場合は不足しているコンテンツを取得するあなたの方法:フィックス –

38
String html = (String) webEngine.executeScript("document.documentElement.outerHTML"); 
+1

この1つのライナーを助けてくださいしてくださいを持っている場合、私はこのトピックについて非常に心配です労働者でなければ働かないだろう。空のhtmlを返します。また、google.comなどのサイトでは機能しません。ライブDOMを返さず、基本的なhtml/javascriptのみを返します。 – Andy

関連する問題