1 回答

TA貢獻1815條經驗 獲得超13個贊
首選大小屬性及其對應的最小/最大屬性都不允許您可靠地確定 a 的大小Region。這些只是指標,計算值可能不匹配。此外,Region可以將其大小調整為首選大小以外的大小。最后但并非最不重要的是,這些屬性可能包含特殊值Region.USE_PREF_SIZE(= Double.NEGATIVE_INFINITY) 和Region.USE_COMPUTED_SIZE(= -1),甚至默認情況下也會這樣做。
如果需要獲取節點的大小,請使用以下boundsInLocal屬性:
Bounds bounds = stackPane.getBoundsInLocal();
在這種情況下,雖然獲取快照的大小更簡單。
此外,頁面大小PDPage可能不足以包含整個圖像。您需要改為縮放圖像或更改PDPage.
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "C:/Users/Andre Kelvin/Desktop/PDFNode.pdf");
這可以HostServices通過Application實例使用可用的平臺獨立完成。
例子
@Override
public void start(Stage primaryStage) {
Button button = new Button("print");
StackPane root = new StackPane(button);
button.setOnAction(evt -> {
try {
WritableImage nodeshot = root.snapshot(new SnapshotParameters(), null);
// store image in-memory
ByteArrayOutputStream output = new ByteArrayOutputStream();
ImageIO.write(SwingFXUtils.fromFXImage(nodeshot, null), "png", output);
output.close();
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
PDImageXObject pdimage;
PDPageContentStream content;
pdimage = PDImageXObject.createFromByteArray(doc, output.toByteArray(), "png");
content = new PDPageContentStream(doc, page);
// fit image to media box of page
PDRectangle box = page.getMediaBox();
double factor = Math.min(box.getWidth() / nodeshot.getWidth(), box.getHeight() / nodeshot.getHeight());
float height = (float) (nodeshot.getHeight() * factor);
// beware of inverted y axis here
content.drawImage(pdimage, 0, box.getHeight() - height, (float) (nodeshot.getWidth() * factor), height);
content.close();
doc.addPage(page);
File outputFile = new File("C:/Users/Andre Kelvin/Desktop/PDFNode.pdf");
doc.save(outputFile);
doc.close();
getHostServices().showDocument(outputFile.toURI().toString());
} catch (Exception e) {
}
});
Scene scene = new Scene(root, 300, 300);
primaryStage.setScene(scene);
primaryStage.show();
}
添加回答
舉報