Print contents of JavaFx TableView


Question

I am looking for a way to print the contents of a JavaFX TableView. I understand that JavaFX doesn't have Printing capabillities just yet (what a disapointment). I have found some information about taking a screenshot of a WebView for example and print it as an image.

Is it possible to do something like that with a Table view. How to go about to handle multiple pages on tables with many data.

Thanks for your help

1
5
5/24/2013 4:06:47 PM

Accepted Answer

Printing API appeared in fx8.0. And it can print nodes. You can create printer job with javafx.print.PrinterJob class. But it prints only region that fits to a printed page, and not the one that you on a screen. So you need to make your node fit page(scale, translate, etc) by hands. Here is simple printing example:

   PrinterJob printerJob = PrinterJob.createPrinterJob();
   if(printerJob.showPrintDialog(primaryStage.getOwner()) && printerJob.printPage(yourNode))
       printerJob.endJob();
6
5/24/2013 4:48:49 PM

Snip the area you want

Rectangle rect = new Rectangle(0,0,dataDisplayAreaAnchorPane.getWidth(),dataDisplayAreaAnchorPane.getHeight());
            dataDisplayAreaAnchorPane.setClip(rect);
            WritableImage writableImage;
            writableImage = new WritableImage((int) dataDisplayAreaAnchorPane.getPrefWidth(),
                    (int) dataDisplayAreaAnchorPane.getPrefHeight());
            dataDisplayAreaAnchorPane.snapshot(null, writableImage);        
            eventDispatcher.printLandscape(writableImage);

**------------------------------------**

Resize according to A4 paper size and print

public void print(WritableImage writableImage, Stage primaryStage) {
            ImageView imageView =new ImageView(writableImage);
            Printer printer = Printer.getDefaultPrinter();
            PageLayout pageLayout = printer.createPageLayout(Paper.A4, PageOrientation.LANDSCAPE, Printer.MarginType.DEFAULT);
            double scaleX = pageLayout.getPrintableWidth() / imageView.getBoundsInParent().getWidth();
            double scaleY = pageLayout.getPrintableHeight() / imageView.getBoundsInParent().getHeight();
            imageView.getTransforms().add(new Scale(scaleX, scaleY));

            PrinterJob job = PrinterJob.createPrinterJob();
            if (job != null) {
                boolean successPrintDialog = job.showPrintDialog(primaryStage.getOwner());
                if(successPrintDialog){
                    boolean success = job.printPage(pageLayout,imageView);
                    if (success) {
                        job.endJob();
                    }
                }
            }
        }

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon