0

I'm developing a javafx application that opens a PDF when I pres a button. I'm using the xdg-open command in linux like this:

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

but when i pres the button nothing happens. I tested it in a different project and it opened the PDF without problem. Any idea how can i fix this?

  • do you want to open the pdf inside the app ? or external with the system defualft program to open pdf ?? – Ivan Fontalvo Oct 30 '18 at 13:56
  • external with the system defualft program – Matyas Kondert Oct 30 '18 at 13:58
  • Non FXML answer [here](https://stackoverflow.com/questions/16604341/how-can-i-open-the-default-system-browser-from-a-java-fx-application). FXML answer [here](https://stackoverflow.com/questions/50774910/gethostservices-showdocument-in-a-fxml-file/50775157#50775157) – SedJ601 Oct 30 '18 at 15:05
  • Possible duplicate of [getHostServices().showDocument() in a FXML File](https://stackoverflow.com/questions/50774910/gethostservices-showdocument-in-a-fxml-file) – SedJ601 Oct 30 '18 at 15:06
  • `getHostServices().showDocument("path\to\your\pdf\file.pdf");` – SedJ601 Oct 30 '18 at 15:07
  • @Sedrick That is not a duplicate **question** (even if the answer may be similar). – Mark Rotteveel Oct 30 '18 at 16:55

3 Answers3

3

Here's the method that I use. A simple call to the Desktop.getDesktop().open() method will open any given File using the system's default application.

This will also open the file in a background Thread so your application doesn't hang while waiting for the file to load.

public static void openFile(File file) throws Exception {
    if (Desktop.isDesktopSupported()) {
        new Thread(() -> {
            try {
                Desktop.getDesktop().open(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
Zephyr
  • 9,885
  • 4
  • 28
  • 63
  • EDIT: I added the `Desktop.isSupported()` check because it is required for some Linux environments. – Zephyr Oct 30 '18 at 14:24
1

This code show the document in the default browser :

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

I hope this help!!

Ivan Fontalvo
  • 433
  • 4
  • 21
0

I have used ICEpdf's org.icepdf.core.pobjects.Document to render the pages of my PDF's; as described here. This gives a ava.awt.image.BufferedImageper page. I convert this to a JavaFX node:

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

ImageView imageView = new ImageView(fxImage);

From there you can write your own simple paging viewer in JavaFX. The rendering is fast and the result looks as hoped for.

  • This does not answer the original question. The OP explicitly asked to open "external with the system defualft program". – mipa Dec 19 '20 at 14:29