-1

I am struggling with opening a PDF file as a user's documentation in JavaFX program.

Code works fine whenever I open it using IDE. The problem begins when I build my program and try to open it from distributions folder.

For example, this method works, when I am using IDE:

public void helpButtonOnAction(ActionEvent actionEvent) {
    File file = new File("src/main/resources/pl/com/buleek/docs.pdf");
    hostServices.showDocument(file.getAbsolutePath());
}

But obviously, when I pack my program with gradle build, it is in a directory: C:\Users\Matthew\Desktop\xxx\ProgramNameFolder\build\distributions\ProgramName\bin

And from now on, it can't see src/main/recources/pl/com/buleek/docs.pdf, because in ProgramNameFolder there are only bin with ProgramName.bat and lib folders.

Is there a way (after building distributions) to paste another folder inside my ProgramName folder, put there my docs.pdf file, and then set code like:

public void helpButtonOnAction(ActionEvent actionEvent) {
    File file = new File("ProgramName/docs/docs.pdf");
    hostServices.showDocument(file.getAbsolutePath());
}

Or shall I use some command to pack pdf file with my program?

buleek
  • 11
  • 1
  • 1
    this looks like basic java, how is it related to javafx (except being used accidentally in the ui context)? Anyway, learn how to lookup resources (see f.i. https://stackoverflow.com/questions/61531317/how-do-i-determine-the-correct-path-for-fxml-files-css-files-images-and-other for starters) - and stick to java naming conventions when showing java code publicly. – kleopatra Feb 14 '22 at 11:08
  • Thank you @jewelsea, everything is clear and working now. – buleek Feb 14 '22 at 13:09

1 Answers1

1

Your build tool will usually place your resources in a jar. As your PDF file is already in your resources folder, it should be packaged into your application jar by default.

You can read resources from your jar file via YourClass.class.getResourceAsStream(), then write the stream to a temp file using basic Java I/O APIs, specifically the version of Files.copy(...) which takes an input stream as a parameter.

The intermediate step of extracting the PDF file from your jar and writing to a temp file in the file system is necessary because you are using host services to launch an external browser and, unlike java, the external browser will be unable to directly read resources from a jar file.

You can convert the file name of the temporary file to a URL string and show it via HostServices.showDocument(uri) as you are currently doing.

If the browser is capable of displaying PDFs (most are) then the PDF will be displayed in the browser, otherwise, the browser will usually allow the user to download the PDF to a file location of their choice on their machine and open the PDF via an external application.

jewelsea
  • 141,332
  • 12
  • 351
  • 391