Javafx图像到PDF转换,使用PDFBox显示一半图像
我已成功地将图像转换为Pdf。我的问题是pdf显示了一半的宽度 我的代码: 我已尝试使用以下行获取根节点的宽度和高度:Javafx图像到PDF转换,使用PDFBox显示一半图像,java,javafx,pdfbox,Java,Javafx,Pdfbox,我已成功地将图像转换为Pdf。我的问题是pdf显示了一半的宽度 我的代码: 我已尝试使用以下行获取根节点的宽度和高度: content.drawImage(pdimage, 0, 0,(float)stackPane.getPrefWidth(),(float)stackPane.getPrefHeight()); 这是: content.drawImage(pdimage, 0, 0,(float)stackPane.getMaxWidth(),(float)stackPane.getMax
content.drawImage(pdimage, 0, 0,(float)stackPane.getPrefWidth(),(float)stackPane.getPrefHeight());
这是:
content.drawImage(pdimage, 0, 0,(float)stackPane.getMaxWidth(),(float)stackPane.getMaxHeight());
它只会显示一个空白的白色页面
这是转换为pdf的实际图像:
这是图片的pdf格式:
无论是首选大小属性还是最小/最大属性都不允许您可靠地确定
区域的大小。这些只是指标,计算值可能不匹配。此外,区域
的大小可以调整为首选大小以外的大小。最后但并非最不重要的一点是,这些属性可能包含特殊值区域。请使用\u PREF\u SIZE
(=Double.NEGATIVE\u INFINITY
)和区域。使用\u COMPUTED\u SIZE
(=-1
)甚至在默认情况下也可以这样做
如果需要获取节点的大小,请使用boundsInLocal
属性:
Bounds bounds = stackPane.getBoundsInLocal();
在这种情况下,获取快照的大小更简单
此外,PDPage
的页面大小可能不足以容纳整个图像。您需要缩放图像,或者更改PDPage
的页面大小
这可以使用独立于平台的
例子
请共享PDF和原始图像,并说明您使用的PDFBox版本。对于宽度和高度,请使用图像大小,并将它们乘以一个因子以获得适当的大小。还要检查您正在保存和删除的png文件(为什么?)是否正确。@TilmanHausherr请参见编辑。我使用的是pdfbox 2.0.12,png图像没有问题。你使用的是宽度因子,而不是高度因子,我想知道这是否看起来很好。效果不错。但它在pdf图像下方增加了一些高度。
Bounds bounds = stackPane.getBoundsInLocal();
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "C:/Users/Andre Kelvin/Desktop/PDFNode.pdf");
@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();
}