package bugs.jpeg; import java.io.File; import java.io.IOException; import javafx.application.Application; import javafx.collections.*; import javafx.embed.swing.SwingFXUtils; import javafx.scene.*; import javafx.stage.Stage; import javafx.scene.chart.*; import javafx.scene.control.Label; import javafx.scene.image.*; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javax.imageio.ImageIO; /** * https://forums.oracle.com/forums/thread.jspa?threadID=2401658&tstart=0 * LineChart in PDF with IText * @author jsmith * See also: http://javafx-jira.kenai.com/browse/RT-22558 * This is a known limitation in CSS and layout processing. In order for either to work correctly * for Node.snapshot(), the node in question must be attached to a Scene. The scene need not be * attached to a Stage, so the following is sufficient, added any time after the chartContainer * is constructed and before snapshot is called: Scene snapshotScene = new Scene(chartContainer); * As part of finishing the API docs for snapshot, this limitation will be documented. */ public class PieChartExport extends Application { private final static String FILE_TYPE = "png"; // "jpeg" or "png" @Override public void start(Stage stage) throws IOException { // create a chart. ObservableList pieChartData = FXCollections.observableArrayList( new PieChart.Data("Grapefruit", 13), new PieChart.Data("Oranges", 25), new PieChart.Data("Plums", 10), new PieChart.Data("Pears", 22), new PieChart.Data("Apples", 30) ); final PieChart chart = new PieChart(pieChartData); chart.setTitle("Imported Fruits"); // render an image of the chart to a file. Pane chartContainer = new Pane(); chartContainer.getChildren().add(chart); chart.setMinSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE); chart.setPrefSize(2000, 2000); chart.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE); chart.setStyle("-fx-font-size: 36px;"); @SuppressWarnings("unused") // Only needed to work around bug (http://javafx-jira.kenai.com/browse/RT-22558). Scene snapshotScene = new Scene(chartContainer); SnapshotParameters params = new SnapshotParameters(); params.setFill(Color.ALICEBLUE); Image image = chartContainer.snapshot(params, null); File file = new File("piechart." + FILE_TYPE); ImageIO.write(SwingFXUtils.fromFXImage(image, null), FILE_TYPE, file); // layout the scene. VBox layout = new VBox(5); layout.getChildren().addAll( new Label("Wrote: " + file.getCanonicalPath()), new ImageView(new Image(file.toURI().toString(), 400, 0, true, true)) ); layout.setStyle("-fx-background-color: white; -fx-padding: 10;"); // show the scene. stage.setScene(new Scene(layout)); stage.show(); } public static void main(String[] args) { launch(args); } }