JavaFX printing non node objects

人走茶凉 提交于 2019-12-21 21:48:53

问题


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();
    }
}

回答1:


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:

Something like:

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();
    }
}

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



来源:https://stackoverflow.com/questions/36981548/javafx-printing-non-node-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!