Praveen
Praveen

Reputation: 43

Open PDF file with default browser in java

Snippet of the code

    public class AnyPlatformAppPDF {

        public static void main(String[] args) {

          try {

            File pdfFile = new File("c:\\Users\\ADMIN\\Desktop\\css\\Praveen_Profile.pdf");
            if (pdfFile.exists()) {

                if (Desktop.isDesktopSupported()) {
                    Desktop.getDesktop().open(pdfFile);
                } else {
                    System.out.println("Awt Desktop is not supported!");
                }

            } else {
                System.out.println("File is not exists!");
            }

            System.out.println("Done");

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

        }

        public static void openWebpage(java.net.URI uri) {
            Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
            if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
                try {
                    desktop.browse(uri);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

I tried this code to open pdf file in browser but it doesn't open the pdf file. I am using Java to do so. How can I fix this?

Upvotes: 3

Views: 4881

Answers (1)

Alican Beydemir
Alican Beydemir

Reputation: 343

Using process builder may solve your problem;

//Windows

ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/C", "explorer c:\\Users\\ADMIN\\Desktop\\css\\Praveen_Profile.pdf");

//Linux

ProcessBuilder processBuilder = new ProcessBuilder("/bin/bash", "-c", "sensible-browser c:\\Users\\ADMIN\\Desktop\\css\\Praveen_Profile.pdf");

//

processBuilder.start();

Upvotes: 4

Related Questions