问题描述
我正在使用 JAVA FX 控件开发 Swing 应用程序.在我的应用程序中,我必须打印出 webview 中显示的 html 页面.我正在尝试的是在 HtmlDocuement 的帮助下将 webview 的 html 内容加载到字符串中.
I am working on a swing application using JAVA FX controls . In my application i have to take print out the html page displayed in the webview . What I am trying is to load the html content of webview in a string with the help of HtmlDocuement.
要从 Web 视图加载 html 文件的内容,我正在使用以下代码但它不起作用:
To load the content of html file from web view,I am using the following code but its not working:
try
{
String str=webview1.getEngine().getDocment().Body().outerHtml();
}
catch(Exception ex)
{
}
推荐答案
WebEngine.getDocument
返回 org.w3c.dom.Document
,而不是您期望判断的 JavaScript 文档通过你的代码.
WebEngine.getDocument
returns org.w3c.dom.Document
, not JavaScript document which you expect judging by your code.
不幸的是,打印org.w3c.dom.Document
需要大量的编码.您可以尝试 中的解决方案将 org.w3c.dom.Document 漂亮地打印到标准输出的最短方法是什么?,请参阅下面的代码.
Unfortunately, printing out org.w3c.dom.Document
requires quite a bit of coding. You can try the solution from What is the shortest way to pretty print a org.w3c.dom.Document to stdout?, see code below.
请注意,在使用Document
之前,您需要等到文档加载完毕.这就是这里使用 LoadWorker
的原因:
Note that you need to wait until the document is loaded before working with Document
. This is why LoadWorker
is used here:
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();
}
这篇关于使用 javafx 从 webview 获取内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!