我正在开发一个使用JAVA FX控件的swing应用程序。在我的应用程序中,我必须打印出网页视图中显示的html页面。我正在尝试的是在HtmlDocuement的帮助下将webview的html内容加载到字符串中。
为了从web视图加载html文件的内容,我使用了以下代码,但它不起作用:
try
{
String str=webview1.getEngine().getDocment().Body().outerHtml();
}
catch(Exception ex)
{
}
发布于 2013-01-12 02:13:09
根据代码判断,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();
}
发布于 2013-12-30 01:29:12
String html = (String) webEngine.executeScript("document.documentElement.outerHTML");
https://stackoverflow.com/questions/14273450
复制相似问题