Opening a PDF in a javafx aplication - java

I'm developing a javafx application that opens a PDF when I pres a button. I'm using the xdg-open command in linux like this:
String[] command = {"xdg-open",path}
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
but when i pres the button nothing happens.
I tested it in a different project and it opened the PDF without problem.
Any idea how can i fix this?

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

This code show the document in the default browser :
File file = new File("C:/filePath/Test.pdf");
HostServices hostServices = getHostServices();
hostServices.showDocument(file.getAbsolutePath());
I hope this help!!

I have used ICEpdf's org.icepdf.core.pobjects.Document to render the pages of my PDF's; as described here. This gives a ava.awt.image.BufferedImageper page. I convert this to a JavaFX node:
Image fxImage = SwingFXUtils.toFXImage(bufferedImage, null);
ImageView imageView = new ImageView(fxImage);
From there you can write your own simple paging viewer in JavaFX. The rendering is fast and the result looks as hoped for.

Related

How to properly set the content of an IFile in Eclipse plugin when the editor is opened

I'm using the following code to set the content of an IFile:
public static IFile updateFile(IFile file, String content) {
if (file.exists()) {
InputStream source = new ByteArrayInputStream(content.getBytes());
try {
file.setContents(source, IResource.FORCE, new NullProgressMonitor());
source.close();
} catch (CoreException | IOException e) {
e.printStackTrace();
}
}
return file;
}
This works fine when the file is not opened in the editor, but if the file is opened I get the following warning as if the file was modified outside of Eclipse:
I tried to refresh the file (by calling refreshLocal() method) before and after calling setContents() but that didn't help.
Is there a way to avoid this warning?
Wrap your method in a WorkspaceModifyOperation.
The editor reaction looks correct, because there is a modification outside of org.eclipse.jface.text.IDocument that bound to the editor instance.
The right approach will be to modify not the file content, but an instance of "model" that represents the file content, something like IJavaElement for JDT.
Also you can try to manipulate the document content directly (needs polishing for production):
IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows();
for (IWorkbenchWindow window : windows) {
IWorkbenchPage[] pages = window.getPages();
for (IWorkbenchPage page : pages) {
IEditorReference[] editorReferences = page.getEditorReferences();
for (IEditorReference editorReference : editorReferences) {
IEditorPart editorPart = editorReference.getEditor(false/*do not restore*/);
IEditorInput editorInput = editorPart.getEditorInput();
//skip editors that are not related
if (inputAffected(editorInput)) {
continue;
}
if (editorPart instanceof AbstractTextEditor) {
AbstractTextEditor textEditor = (AbstractTextEditor) editorPart;
IDocument document = textEditor.getDocumentProvider().getDocument(editorInput);
document.set(content);
}
}
}
}
Honestly, I do not understand the scenario you are trying to cover, probably there are better ways to do this.

Why should I use Platform.runlater on javafx main thread in this code?

I'm making java application with javaFx ui in kind of tiny machine. I wanted to show loading page, and load data files during the progress indicator going on.
I know it could work well if I added Platform.runlater on the code loading fxml file and controller, but it's weird for me to use Platform.runlater on javaFx main app thread. I checked threads' name but they were same. Also it works if it run separately using annotation.
Why do i need to use Platform.runlater ?
If I don't add that, loading image turns white screen and skip image, and just show menu view.
//Process
//1. Set loading page image
//2. Load data files
//3. Load next page(menu)
public void loadHomeMenuPage() {
setLoadingImage();
execLoadingData();
execLoadingView(this);
}
private void setLoadingImage() {
System.out.println("Load -> " + Thread.currentThread());
File file = new File("Resources/images/load.png");
InputStream is;
try
{
is = new FileInputStream(file);
this.logoImageView.setImage(new Image(is));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
private void execLoadingData() {
// load openCv files
new LoadOpenCV();
// load protocol files
new ProtocolLoader().load();
// load language pack here
}
private void execLoadingView(IController loadController) {
//Load homeMenu after loading all data
//Platform.runLater(() -> {
System.out.println(Thread.currentThread());
IController controller = (IController) FxmlUtils.LOAD
.fxmlPath(PathFxml.ABS_PATH_HOME_MENU_VIEW)
.pane("BorderPane")
.set2BaseBorderPane(this.baseBorderPane, "center")
.exec();
controller.setBaseBorderPane(this.baseBorderPane);
//});
}

Image/File upload path after making app in Java from Eclipse

I am making a Java-SQL database storing app on Eclipse and MySQL. In this app, I have to upload image to the file directory. Currently while making this app, I am using an image upload path and storing all the uploaded images there. But when I'm finished with the app, and if I'm to work it on someone else's computer the image upload path in the code obviously will not work on that computer. What shall I do to make it work on other computer as well? Should I make a prompt which asks for image upload path every time the app opens and store that, or something else?? please help.
private String imageUploadPath = "/home/tsoprano/Documents/eclipse-workspace/enable/src/com/enable/regis/imgupload/";
File file1;
picLabel = new JLabel(" Upload Photo");
picLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
JFileChooser imageChooser= new JFileChooser();
if(imageChooser.showOpenDialog(picLabel)==JFileChooser.APPROVE_OPTION) {
file1 = imageChooser.getSelectedFile();
ImageIcon icon= new ImageIcon(imageChooser.getSelectedFile().getPath());
Image img=icon.getImage().getScaledInstance(130, 150, Image.SCALE_SMOOTH);
icon= new ImageIcon(img);
picLabel.setIcon(icon);
}
}
});
//inside the submit button action
String filePath = imageUploadPath + file1.getName();
try {
BufferedImage bi = ImageIO.read(file1);
ImageIO.write(bi, "jpg", new File(filePath));
} catch (IOException e1) {
e1.printStackTrace();
}
rdto.setPicUrl(filePath);
I would not suggest doing this via a config file, because this is not very user-friendly. Instead, get the current directory (i. e. the one that you executed the java command) using System.getProperty("user.dir"). Then create a new folder inside there, and use it as your upload folder. This will make sure you always have a useable path without bothering the user with specifying it.

showDocument() does not display new window in IE8 with Java 7/Java 6u27

I have a Java Applet that interacts with the Java Plugin to show a document (just a URL) in a named browser window:
public class TestApplet extends Applet {
#Override
public void init() {
super.init();
final JButton showButton = new JButton("Show Google!");
showButton.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
try {
getAppletContext().showDocument(new URL("http://google.com"), "Some Window Title");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
}
});
add(showButton);
}
}
This has worked historically but starting with Java 7 and Java 6u27, the window fails to open in Internet Explorer (tested in IE 8). If I use _blank as the window title (target) instead of Google, the window opens correctly (albeit in a new window each time).
I've tracked down this bug that was fixed for 6u27:
Vista/IE7 further showDocument focus issue with named targeted windows
Has anybody else experienced the same behaviour? Have you found a workaround (other than using "_blank")?
Edit
Updated the example. I wasn't actually using "Google" as the target, I was using "Some Window Title" (sorry!). It seems like this problem is unique to targets with spaces in the name.
It seems like this problem is unique to targets with spaces in the name.
Two possible solutions:
Replace the " " with "%20"
Don't use a space in the name of the target! (Though I thought that would be a 'no brainer'.)
Try this code, it should work.
Desktop desktop = Desktop.getDesktop();
desktop.browse(new URI(info));

Accessing a PDF in Jar

I'm creating a Java application using Netbeans. From the 'Help' Menu item, I'm required to open a PDF file. When I run the application via Netbeans, the document opens, but on opening via the jar file, it isn't opening. Is there anything that can be done?
m_aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Runtime rt = Runtime.getRuntime();
URL link2=getClass().getResource("/newpkg/Documentation.pdf");
String link=link2.toString();
link=link.substring(6);
System.out.println(link);
System.out.println(link2);
String link3="E:/new/build/classes/newpkg/Documentation.pdf";
try {
Process proc = rt.exec("rundll32.exe url.dll,FileProtocolHandler " + link3);
} catch (IOException ex) {
Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
The two outputs are as follows:
E:/new/build/classes/newpkg/Documentation.pdf
file:/E:/new/build/classes/newpkg/Documentation.pdf
Consider the above code snippet. On printing 'link',we can see that it is exactly same as the hard coded 'link3'. On using the hard coded 'link3' , the PDF file gets opened from jar application. But when we use link, though it is exactly same as 'link3', the PDF doesn't open.
This is most likely related to the incorrect PDF resource loading. In the IDE you have the PDF file either as part of the project structure or with a directly specified relative path. When a packaged application is running it does not see the resource.
EDIT:
Your code reveals the problem as I have described. The following method could be used to properly identify resource path.
public static URL getURL(final String pathAndFileName) {
return Thread.currentThread().getContextClassLoader().getResource(pathAndFileName);
}
Pls refer to this question, which might provide additional information.
Try out this:
m_aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
URL link2=Menubar1.class.getResource("/newpkg/Documentation.pdf");
String link=link2.toString();
link=link.substring(6);
System.out.println(link);
File file=new File(link);
System.out.println(file);
try {
desktop.open(file);
} catch (IOException ex) {
Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});

Categories