printingjavafx-8pdfrenderer

JavaFX printing non node objects


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

Solution

  • 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.