JavaFX打印非节点对象 [英] JavaFX printing non node objects

查看:60
本文介绍了JavaFX打印非节点对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印一个 PDFFile 对象"rel =" nofollow> Pdf-Renderer 库使用javafx打印.是否可以打印非 Node 对象?目前,我正在使用AWT打印(检查此示例),但是它不适用于javafx,因为当出现AWT打印对话框时,我的javafx窗口会冻结.

I want to print a 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) but it doesn't go well with javafx because my javafx window freezes when the AWT print dialog comes up.

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:

You can get a java.awt.Image from each page, draw the page to a java.awt.image.BufferedImage convert the BufferedImage to a javafx.scene.image.Image, and finally print an ImageView containing the image:

类似的东西:

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 Application Thread之外执行此代码,以使UI保持响应状态.

Note that this code can be executed off the FX Application Thread, to keep the UI responsive.

这篇关于JavaFX打印非节点对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆