JavaFx,打印 PDF(来自 PDFBOx)

发布于 2025-01-16 07:55:59 字数 616 浏览 2 评论 0原文

我有一个 JavaFX 应用程序,可以使用 Apache PDFBox 生成 PDF。我想打印该 PDF。

但是,我无法找到好的解决方案。

我尝试过使用 java.awt.print.PrinterJob,但在调用 PrinterJob#printDialog(..) 方法时它会挂起。鼠标光标变为“等待”,我无法再使用该应用程序。

我尝试过使用javafx.print.PrinterJob。它可以显示打印对话框,但我找不到打印节点以外的内容的方法。

此时,我使用 java.awt.Desktop API 进行打印。它打印我的 PDF,但跳过打印对话框。

所以,我的问题是:如何从 JavaFX 显示打印对话框并打印 PDF(最好是 org.apache.pdfbox.pdmodel.PDDocument)?

我的项目使用 Java 17(Open Jdk)和 JavaFX 16。我在 MacOS 上遇到问题,从未在其他操作系统上尝试过。

我还可以将其写入磁盘并打印文件或将其转换为任何类型的流,而不是打印PDDocument

多谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦开始←不甜 2025-01-23 07:55:59

这个问题,正如@Saw所启发的那样,是因为我没有尝试从 EDT 打开 AWT 打印对话框。

解决方案是将该代码包装到提交给 SwingUtilities.invokeLaterRunnable 中:

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

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();
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文