javajavafxjavafx-webengine

Printing a javafx WebEngine's content on multiple pages


I want to print the content of a WebEngine:

PrinterJob job = PrinterJob.createPrinterJob();
job.getJobSettings().setJobName("Print WebEngine");
job.getJobSettings().setPageLayout(job.getPrinter().createPageLayout(Paper.A4, PageOrientation.PORTRAIT, MarginType.DEFAULT));

webEngine.print(job);

job.endJob();

Unfortunately, my printer only prints one page although there is much more content loaded, which should be printed on further pages. Additionally, the content which was printed on the single page is distorted on the result.

Does anyone know how I can print the whole content of the WebEngine on many pages so that it is not scaled or something like this?


Solution

  • I am able to print multiple pages using the code you have. The first print will print Google's home page. That's one page. Type test into the search bar and press enter. This should return two printable pages.

    //https://docs.oracle.com/javase/8/javafx/embedded-browser-tutorial/printing.htm
    //http://tutorials.jenkov.com/javafx/webview.html
    
    
    
    import javafx.application.Application;
    import javafx.concurrent.Worker;
    import javafx.print.PrinterJob;
    import javafx.scene.Scene;
    import javafx.scene.layout.VBox;
    import javafx.scene.web.WebEngine;
    import javafx.scene.web.WebView;
    import javafx.stage.Stage;
    
    public class App extends Application {
    
        public static void main(String[] args) {
            launch(args);
        }
    
        @Override
        public void start(Stage primaryStage) {
            primaryStage.setTitle("JavaFX WebView Example");
    
            WebView webView = new WebView();
            WebEngine webEngine = webView.getEngine();        
            webEngine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> {
                System.out.println("oldValue: " + oldValue);
                System.out.println("newValue: " + newValue);
                
                if (newValue == Worker.State.SUCCEEDED) {
                    PrinterJob printerJob = PrinterJob.createPrinterJob();
                    if(printerJob != null)
                    {
                        printerJob.showPrintDialog(primaryStage);
                        webEngine.print(printerJob);
                        printerJob.endJob();
                    }                
                }
            });
            
            webEngine.load("http://google.com");
            
    
            VBox vBox = new VBox(webView);
            Scene scene = new Scene(vBox, 960, 600);
    
            primaryStage.setScene(scene);
            primaryStage.show();
    
        }
    }