有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在javafx应用程序中打开PDF

我正在开发一个javafx应用程序,当我按下按钮时,它会打开一个PDF。我在linux中使用xdg open命令,如下所示:

String[] command = {"xdg-open",path}
Process p = Runtime.getRuntime().exec(command);
p.waitFor();

但当我按下按钮时,什么也没发生。 我在另一个项目中测试了它,它毫无问题地打开了PDF。 你知道我该怎么解决这个问题吗


共 (3) 个答案

  1. # 1 楼答案

    我已经使用ICEpdf的org.icepdf.core.pobjects.Document来呈现我的PDF的页面as described here。这将为每页提供一个ava.awt.image.BufferedImage。我将其转换为JavaFX节点:

    Image fxImage = SwingFXUtils.toFXImage(bufferedImage, null);

    ImageView imageView = new ImageView(fxImage);

    从那里,您可以用JavaFX编写自己的简单分页查看器。渲染速度很快,结果与预期一致

  2. # 2 楼答案

    这是我使用的方法。对Desktop.getDesktop().open()方法的简单调用将使用系统的默认应用程序打开任何给定的File

    这还将在后台Thread中打开文件,以便在等待加载文件时应用程序不会挂起

    public static void openFile(File file) throws Exception {
        if (Desktop.isDesktopSupported()) {
            new Thread(() -> {
                try {
                    Desktop.getDesktop().open(file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
    
  3. # 3 楼答案

    此代码在默认浏览器中显示文档:

    File file = new File("C:/filePath/Test.pdf");
    HostServices hostServices = getHostServices();
    hostServices.showDocument(file.getAbsolutePath());
    

    我希望这有帮助