JavaFX 打印非节点对象

JavaFX printing non node objects

我想打印一个 PDFFile object from the Pdf-Renderer library using javafx printing. Is it possible to print non Node objects? Currently i'm using AWT printing (check this example) 但它与 javafx 不兼容,因为当 AWT 打印对话框出现时我的 javafx window 冻结了。

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 响应。