Domanda

I am writing a JavaFX application that uses WebView to access a website and extract data from its pages. At some point I want to click on a link that opens up a new window which shows a PDF file. With the luck of PDF support in JavaFX I am thinking that one possible solution might be to read the http response for that PDF and create the PDF form the binary data.

The url of the PDF page is dynamic so I don't have the actual name of the file and so I can't use a third party tools to generate the pdf.

Any thoughts would be much appreciated.

Thanks

È stato utile?

Soluzione

Launch a Swing Based PDF Viewer

Here is a code extract from a small web browser (named the willow-browser) I wrote in JavaFX:

webEngine.locationProperty().addListener(new ChangeListener<String>() {
  @Override public void changed(ObservableValue<? extends String> observableValue, String oldLoc, String newLoc) {
    if (newLoc.endsWith(".pdf")) {
      try {
        final PDFViewer pdfViewer = new PDFViewer(false);
        pdfViewer.openFile(new URL(newLoc));
      } catch (Exception ex) {
        // handle bad pdf url . . . most likely no action required
      }
    }
  }
}

The code makes use of a 3rd party Swing based pdf viewer which it launches to load the url. As the Swing pdf viewer runs in a seperate window, there were not any Swing/JavaFX integration issues around it - it just seemed to work.

To get it to work, you can download a copy of the willow browser source and build it (the sample binary hosted on the site doesn't include the pdf viewer, only the source builds do).

Ideally, the code would query the http content type in addition to the uri string to determine that the file is a pdf, but that requires a bit of low level network access which is difficult to get at in the case of WebView. If you are not concerned about being perfectly accurate at detecting pdf content on many sites, it won't really matter if you don't make use of the content type to determine pdfs.

There are other pdf viewers around which you could try if the Swing pdf viewer doesn't provide you with the experience you want, e.g. jpedalfx or ICEpdf.

Launch a Native PDF Viewer

If you prefer you could call HostServices.showDocument(uri) on the pdf url and that will trigger to open the url in a local web browser, some of which have built in pdf viewers or are setup to view the pdf using the Acrobat reader.

The code to determine the url for the pdf to view is the same in this case as the code above.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top