Created
February 11, 2020 05:34
-
-
Save tresf/7b2ebc3f7fcff1c6dd977cf505362bdc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import javafx.animation.AnimationTimer; | |
import javafx.application.Application; | |
import javafx.concurrent.Worker; | |
import javafx.embed.swing.SwingFXUtils; | |
import javafx.scene.Scene; | |
import javafx.scene.web.WebView; | |
import javafx.stage.Stage; | |
import javax.imageio.ImageIO; | |
import java.io.File; | |
public class ResizeBeforeShow extends Application { | |
public static void main(String[] args) { | |
launch(args); | |
} | |
@Override | |
public void start(Stage stage) { | |
WebView webView = new WebView(); | |
webView.setPrefSize(100, 0); | |
webView.setMinSize(100, 0); | |
webView.autosize(); | |
webView.getEngine().loadContent("<html style='background-color: red;'><h1>test1<br></h1><p>testing<br><br><br><br></p></html>"); | |
webView.getEngine().getLoadWorker().stateProperty().addListener((ov, oldState, newState) -> { | |
if (newState == Worker.State.SUCCEEDED) { | |
String height = webView.getEngine().executeScript("Math.max(document.body.offsetHeight, document.body.scrollHeight)").toString(); | |
Double prefHeight = Double.parseDouble(height); | |
System.out.println("Setting height as " + prefHeight); | |
webView.setPrefHeight(prefHeight); | |
webView.setMinHeight(prefHeight); | |
stage.setScene(new Scene(webView)); | |
stage.show(); | |
// Snapshot on next pulse to allow render | |
new AnimationTimer() { | |
@Override | |
public void handle(long now) { | |
webView.snapshot(param -> { | |
try { | |
File outputfile = new File(System.getProperty("user.home") + "/Desktop/a.png"); | |
ImageIO.write(SwingFXUtils.fromFXImage(param.getImage(), null), "png", outputfile); | |
} catch (Throwable t) { | |
t.printStackTrace(); | |
} | |
return null; | |
}, null, null); | |
} | |
}.start(); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment