'JavaFx, printing PDF (From PDFBOx)

I have a JavaFX application that generates a PDF with Apache PDFBox. And I would like to print that PDF.

However, I was not able to find a good solution.

I have tried with the java.awt.print.PrinterJob but it hangs when calling the PrinterJob#printDialog(..) method. The mouse cursor becomes "wait" and I cannot use the application anymore.

I have tried with javafx.print.PrinterJob. It can show the print dialog but I do not find a way to print something else than a node.

At this time, I print with the java.awt.Desktop API. It print my PDF but skip the print dialog.

So, my question is: How can I display the print dialog and print a PDF (ideally an org.apache.pdfbox.pdmodel.PDDocument) from JavaFX?

My project uses Java 17 (Open Jdk) and JavaFX 16. I have the issue on MacOS and never tried on other OS.

Instead of printing the PDDocument I can also write it to he disk and print the File or convert it to any kind of stream.

Thanks a lot



Solution 1:[1]

The issue, as enlighted by @Saw, was because I was not trying to open the AWT print dialog from the EDT.

The solution is to wrap that code into a Runnable submitted to SwingUtilities.invokeLater:

SwingUtilities.invokeLater(() -> {
    var job = PrinterJob.getPrinterJob();
    job.setJobName(report.getTitle());
    job.setPageable(new PDFPageable(report.getDocument()));
    if (job.printDialog()) {
        job.print();
    }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gervais.b