我想使用javafx打印从Pdf Renderer库打印一个PDFFile对象。是否可以打印非节点对象?目前我正在使用AWT打印(查看这个例子),但它与javafx不太配合,因为当AWT打印对话框出现时,我的javafx窗口会冻结。
Printer printer = Printer.getDefaultPrinter();
PageLayout pageLayout = printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.DEFAULT);
PrinterJob job = PrinterJob.createPrinterJob();
if (job != null) {
boolean success = job.printPage(node); // use something otherthan a node(PDFFile in my case)
if (success) {
job.endJob();
}
}
您可以从每个页面获取一个java.awt.Image
,将页面绘制为java.awt.image.BufferedImage
,将BufferedImage
转换为javafx.scene.image.Image
,最后打印一个包含图像的ImageView
:
类似于:
PrinterJob job = PrinterJob.createPrinterJob();
PDFFile pdfFile = ... ;
if (job != null) {
boolean success = true ;
for (int pageNumber = 1; pageNumber <= pdfFile.getNumPages() ; pageNumber++) {
PDFPage page = pdfFile.getPage(pageNumber, true);
Rectangle2D bounds = page.getBBox();
int width = (int) bounds.getWidth();
int height = (int) bounds.getHeight();
java.awt.Image img = page.getImage(width, height, bounds, null, true, true);
BufferedImage bImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bImg.createGraphics().drawImage(img, 0, 0, null);
javafx.scene.image.Image fxImg = SwingFXUtils.toFXImage(bImg, null);
ImageView imageView = new ImageView(fxImg);
success = success & job.printPage(imageView);
}
if (success) {
job.endJob();
}
}
请注意,此代码可以在FX应用程序线程之外执行,以保持UI的响应性。