0

I want to open a pdf file and display it on new window when a button is clicked i try this an it is not working:

Button btn = new Button();

File file=new File("Desktop/Test.pdf");
btn.setText("Open");

btn.setOnAction(new EventHandler<ActionEvent>() {

    public void handle(ActionEvent event) {

        try {
            desktop.open(file);
        } catch (IOException ex) {
            Logger.getLogger(Exemple.class.getName())
                .log(Level.SEVERE, null, ex);
        }
    }
});
James_D
  • 201,275
  • 16
  • 291
  • 322
deep_geek
  • 337
  • 2
  • 4
  • 13

2 Answers2

6

You can try this way to open a PDF file:

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

If you want to use FileChooser, then use this:

btn.setOnAction(new EventHandler<ActionEvent>()
{
    @Override
    public void handle(ActionEvent event)
    {
        FileChooser fileChooser = new FileChooser();

        // Set Initial Directory to Desktop
        fileChooser.setInitialDirectory(new File(System.getProperty("user.home") + "\\Desktop"));

        // Set extension filter, only PDF files will be shown
        FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("PDF files (*.pdf)", "*.pdf");
        fileChooser.getExtensionFilters().add(extFilter);

        // Show open file dialog
        File file = fileChooser.showOpenDialog(primaryStage);

        //Open PDF file
        HostServices hostServices = getHostServices();
        hostServices.showDocument(file.getAbsolutePath());
    }
});
Rana Depto
  • 721
  • 3
  • 11
  • 31
  • 1
    Where's the `getHostServices` method body? – Sameen Jul 10 '17 at 15:02
  • 1
    @orion_IX, `getHostServices()` is a default method of `HostServices` class. Just import `javafx.application.HostServices` in your class and you will find your answer. – Rana Depto Jul 10 '17 at 20:33
  • To clarify this, as I also ran into issues: `getHostServices()` is a method of the `Application` class [API](https://docs.oracle.com/javase/8/javafx/api/javafx/application/Application.html#getHostServices--) of your JavaFX primary class `public class ... extends Application {`, hence you can only instantiate it there. If you need it in another Java class, you have to pass it like shown [here](https://stackoverflow.com/a/33100968/2642801). – SourceSeeker Nov 11 '18 at 13:22
0

If you are using windows you need to fix the path of the file like this:

File file=new File("C:\\Users\\USER\\Desktop\\Test.pdf");

You need to change USER with your windows user.

Also, note that \ is used for escape sequences in programming languages.

mrsfy
  • 13
  • 4