如何在Netbeans中打开PDF文件?

时间:2021-06-11 20:44:37

I want my application to open a pdf file when I click a dedicated button. How would i approach this? Also if I run the application from netbeans it shows the pdf but when compiled nothing comes up?

我希望我的应用程序在单击专用按钮时打开pdf文件。我该如何处理?此外,如果我从netbeans运行应用程序,它显示pdf,但编译时没有出现?

My code

    private void showHelpMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        File f = new File("ana.pdf");
    try {
      Desktop.getDesktop().open(f);
  } catch (Exception ex) {
    System.out.println(ex);}

2 个解决方案

#1


You can explicitly give the entire file path, which might solve your problem. Also the OS you are using must support the operation. This might help:

您可以显式提供整个文件路径,这可能会解决您的问题。您使用的操作系统也必须支持该操作。这可能有所帮助:

if (Desktop.isDesktopSupported()) {
                    try {
                        File myFile = new File("C:\\Users\\klinks\\Documents\\pdf.pdf");
                        Desktop.getDesktop().open(myFile);
                    } catch (IOException e) {
                        // System probably doesn't have a default PDF program
                    }
                }

#2


Your code gets the file from the current directory. The file is there when you run it from netbeans, but the file is not there when you run it.

您的代码从当前目录获取文件。当您从netbeans运行它时,该文件就在那里,但是当您运行它时该文件不存在。

Unfortunately, there's no easy way to do this. I think the best idea would be write the documentation as HTML, put it on a server, and open the web browser (using Desktop.browse). If someone else has a better idea, please comment.

不幸的是,没有简单的方法可以做到这一点。我认为最好的想法是将文档编写为HTML,将其放在服务器上,然后打开Web浏览器(使用Desktop.browse)。如果其他人有更好的想法,请发表评论。

#1


You can explicitly give the entire file path, which might solve your problem. Also the OS you are using must support the operation. This might help:

您可以显式提供整个文件路径,这可能会解决您的问题。您使用的操作系统也必须支持该操作。这可能有所帮助:

if (Desktop.isDesktopSupported()) {
                    try {
                        File myFile = new File("C:\\Users\\klinks\\Documents\\pdf.pdf");
                        Desktop.getDesktop().open(myFile);
                    } catch (IOException e) {
                        // System probably doesn't have a default PDF program
                    }
                }

#2


Your code gets the file from the current directory. The file is there when you run it from netbeans, but the file is not there when you run it.

您的代码从当前目录获取文件。当您从netbeans运行它时,该文件就在那里,但是当您运行它时该文件不存在。

Unfortunately, there's no easy way to do this. I think the best idea would be write the documentation as HTML, put it on a server, and open the web browser (using Desktop.browse). If someone else has a better idea, please comment.

不幸的是,没有简单的方法可以做到这一点。我认为最好的想法是将文档编写为HTML,将其放在服务器上,然后打开Web浏览器(使用Desktop.browse)。如果其他人有更好的想法,请发表评论。