Displaying PDF in Javafx

Displaying pdf in JavaFX

JPedalFX Sample Code and Usage

Sample code on using JPedalFX is provided with the JPedalFX download.

Kind of lame on my part, but I'll just paste snippets sample code here that have been copied from the sample viewer provided with the JPedalFX library. The code relies on the jpedal_lgpl.jar file included with the JPedalFX distribution being on the classpath (or the library path referenced in the manifest of your application jar).

Should you have further questions regarding usage of JPedalFX, I suggest you contact IDR solutions directly (they have been responsive to me in the past).

// get file path.
FileChooser fc = new FileChooser();
fc.setTitle("Open PDF file...");
fc.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF Files", "*.pdf"));
File f = fc.showOpenDialog(stage.getOwner());
String filename = file.getAbsolutePath();

// open file.
PdfDecoder pdf = new PdfDecoder();
pdf.openPdfFile(filename);
showPage(1);
pdf.closePdfFile();

. . .

/**
* Update the GUI to show a specified page.
* @param page
*/
private void showPage(int page) {

//Check in range
if (page > pdf.getPageCount())
return;
if (page < 1)
return;

//Store
pageNumber = page;

//Show/hide buttons as neccessary
if (page == pdf.getPageCount())
next.setVisible(false);
else
next.setVisible(true);

if (page == 1)
back.setVisible(false);
else
back.setVisible(true);

//Calculate scale
int pW = pdf.getPdfPageData().getCropBoxWidth(page);
int pH = pdf.getPdfPageData().getCropBoxHeight(page);

Dimension s = Toolkit.getDefaultToolkit().getScreenSize();

s.width -= 100;
s.height -= 100;

double xScale = (double)s.width / pW;
double yScale = (double)s.height / pH;
double scale = xScale < yScale ? xScale : yScale;

//Work out target size
pW *= scale;
pH *= scale;

//Get image and set
Image i = getPageAsImage(page,pW,pH);
imageView.setImage(i);

//Set size of components
imageView.setFitWidth(pW);
imageView.setFitHeight(pH);
stage.setWidth(imageView.getFitWidth()+2);
stage.setHeight(imageView.getFitHeight()+2);
stage.centerOnScreen();
}

/**
* Wrapper for usual method since JFX has no BufferedImage support.
* @param page
* @param width
* @param height
* @return
*/
private Image getPageAsImage(int page, int width, int height) {

BufferedImage img;
try {
img = pdf.getPageAsImage(page);

//Use deprecated method since there's no real alternative
//(for JavaFX 2.2+ can use SwingFXUtils instead).
if (Image.impl_isExternalFormatSupported(BufferedImage.class))
return javafx.scene.image.Image.impl_fromExternalImage(img);

} catch(Exception e) {
e.printStackTrace();
}

return null;
}

/**
* ===========================================
* Java Pdf Extraction Decoding Access Library
* ===========================================
*
* Project Info: http://www.jpedal.org
* (C) Copyright 1997-2008, IDRsolutions and Contributors.
*
* This file is part of JPedal
*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

*
* ---------------
* JPedalFX.java
* ---------------
*/

SwingLabs PDF Renderer

Additionaly, I used an old SwingLabs Swing based pdf renderer with JavaFX in the past for rendering pdf's for my JavaFX web browser. Although the Swing/JavaFX integration wasn't a supported feature of JavaFX at the time that I developed the browser, it still worked fine for me. Code for integration is in PDFViewer.java and BrowserWindow.java.

Note that embedding JavaFX in a Swing app is supported in Java 2.2 and embedding a Swing app in JavaFX is supported in Java 8.

How to open a PDF file javafx

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());
}
});

Opening a PDF in a javafx aplication

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();
}
}

How do I use Java fx pdf viewer?

Try the JPedalFX viewer which provides a JavaFX component for viewing PDF files.

OR

Pre-convert the PDF into JavaFX code prior to viewing using the JPedal PDF to JavaFX converter.

Displaying Pdf in Javafx using PDFJS library in Webview

I had the same problem: No text would render properly in the JavaFX WebView using the current stable release of PDF.js as of today (v2.0.943). Image based PDFs render properly.

Having a look at the PDF.js release notes, I found that v2.0.943 introduced lots of changes related to fonts and seem to have broken the font rendering in JavaFX.

The good news is that the current pre-release, v2.1.266 has some bugfixes regarding the handling of fonts and it fixes the text rendering problem in the JavaFX WebView.

If you don't feel confortable using a pre-release, you can use v1.10.100, text rendering works with this version too, although I recommend using the latest version, because it seems to render the different fonts much better.

Open Source PDFViewer Javafx

I just created an app you can check out. Here. You could probably find a free application that converts PDF to HTML. This conversion was done using https://www.idrsolutions.com/online-pdf-to-html5-converter/. I personally use Acrobat Reader to convert my files and I am currently trying to implement all of the different functions I want my app to have.

import java.io.File;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

/**
*
* @author blj0011
*/
public class PDFToHTMLExampleApp extends Application
{

@Override
public void start(Stage primaryStage)
{
File file = new File("CookBook/index.html");

WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
webEngine.load(file.toURI().toString());

StackPane root = new StackPane();
root.getChildren().add(webView);

Scene scene = new Scene(root, 700, 1000);

primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}

/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}

}

The reason I chose this site for conversion over others is that they already have a zoom function and a function to handle the pages. The downfall is that they have disabled the search function.
Sample Image



Related Topics



Leave a reply



Submit