Hello,
I need to view PDF's in my JAVA application. After some research, setting aside paid components, it seemed to me that the best answer would be this:
The colleague suggests using the [PDF.js][2]
library running within WebView
.
I was able to view simple PDFs (where there is only text), but I can not see PDFs with images. It looks like it can not load the contents of the entire file.
Some images:
Original example - Using mozilla demo ( link )
Javaapplication-ExamplePDFwithimages:
Javaapplication-simplePDFexample(onlywithtext):
Codeused:
importjava.io.File;importjava.net.MalformedURLException;importjava.net.URISyntaxException;importjava.util.Base64;importjava.util.logging.Level;importjava.util.logging.Logger;importjavafx.application.Application;importjavafx.concurrent.Worker;importjavafx.scene.Scene;importjavafx.scene.layout.StackPane;importjavafx.scene.web.WebEngine;importjavafx.scene.web.WebView;importjavafx.stage.Stage;importorg.apache.commons.io.FileUtils;publicclassBrowserShowPdfextendsApplication{@Overridepublicvoidstart(StageprimaryStage){WebViewwebView=newWebView();WebEngineengine=webView.getEngine();//Changethepathaccordingtoyours.engine.setJavaScriptEnabled(true);Filefile;try{file=newFile(getClass().getResource("viewer.html").toURI());
System.out.println("Url ->>>>>" + file.toURI().toURL().toString());
engine.load(file.toURI().toURL().toString());
} catch (MalformedURLException ex) {
Logger.getLogger(BrowserShowPdf.class.getName()).log(Level.SEVERE, null, ex);
} catch (URISyntaxException ex) {
Logger.getLogger(BrowserShowPdf.class.getName()).log(Level.SEVERE, null, ex);
}
StackPane root = new StackPane();
root.getChildren().add(webView);
engine.getLoadWorker()
.stateProperty()
.addListener((observable, oldValue, newValue) -> {
// this pdf file will be opened on application startup
if (newValue == Worker.State.SUCCEEDED) {
try {
// readFileToByteArray() comes from commons-io library
byte[] data = FileUtils.readFileToByteArray(new File("D:\Font Awesome Cheatsheet.pdf"));
String base64 = Base64.getEncoder().encodeToString(data);
// call JS function from Java code
engine.executeScript("openFileFromBase64('" + base64 + "')");
} catch (Exception e) {
e.printStackTrace();
}
}
});
Scene scene = new Scene(root, 900, 800);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
Some help?
Is there any more practical way to view PDF's within java applications?
Thank you