22

私はJAVAFXコントロールを使用してswingアプリケーションに取り組んでいます。私のアプリケーションでは、Webビューに表示されているHTMLページを印刷する必要があります。私が試しているのは、HtmlDocuementを使用して、WebビューのHTMLコンテンツを文字列にロードすることです。

Webビューからhtmlファイルのコンテンツをロードするために、次のコードを使用していますが、機能していません。

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

2 に答える 2

46
String html = (String) webEngine.executeScript("document.documentElement.outerHTML");
于 2013-12-29T17:29:11.917 に答える
23

WebEngine.getDocumentorg.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();
}
于 2013-01-11T18:13:08.887 に答える