2014-11-25 76 views
0

我在项目位置如何打开PDF文件PDF如何使用vaadin代码在项目文件夹中打开pdf文件?

我的项目名称为MyProject的

我的PDF是项目文件夹

MyProject的\ PDF阅读器\如何检验.pdf打开我的PDF文件下

我需要在项目的位置来打开PDF文件

我曾尝试下面的代码

final Button viewBtn= new Button("View Policy Schedule");  
viewBtn.addClickListener(newButton.ClickListener()          public void buttonClick(ClickEvent event) { 
     Window window = new Window(); 
     window.setResizable(true); 
     window.setCaption("Claim Form Covering Letter PDF"); 
     window.setWidth("800"); 
     window.setHeight("600"); 
     window.setModal(true); 
     window.center(); 
     final String filepath = "Pdf//test.pdf"; 

     File f = new File(filepath); 

     System.out.println(f.getAbsolutePath()); 
     Path p = Paths.get(filepath); 
     String fileName = p.getFileName().toString(); 


     StreamResource.StreamSource s = new StreamResource.StreamSource() { 

      /** 
      * 
      */ 
      private static final long serialVersionUID = 9138325634649289303L; 

      public InputStream getStream() { 
       try { 

        File f = new File("."); 
        System.out.println(f.getCanonicalPath()); 
        FileInputStream fis = new FileInputStream(f); 
        return fis; 

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

     StreamResource r = new StreamResource(s, fileName); 
     Embedded e = new Embedded(); 
     e.setSizeFull(); 
     e.setType(Embedded.TYPE_BROWSER); 
     r.setMIMEType("application/pdf"); 
     e.setSource(r); 
     window.setContent(e); 
     UI.getCurrent().addWindow(window); 
} 
}); 

这不工作我有一个文件没有发现异常

回答

0

移动PDF,以便您可以从类路径中读取它。如果你使用Maven把它放在src/main/resources中。否则把它放在一些包里。

然后,您可以使用java.lang.class的getResourcesAsStream()方法读取它。

InputStream in = this.getClass().getResourcesAsStream("/test.pdf"); //classpath root 
InputStream in = this.getClass().getResourcesAsStream("/my/package/name/test.pdf"); //from some package 

更新

final Button viewBtn= new Button("View Policy Schedule");  
    viewBtn.addClickListener(newButton.ClickListener() 
     public void buttonClick(ClickEvent event) { 
      Window window = new Window(); 
      window.setResizable(true); 
      window.setCaption("Claim Form Covering Letter PDF"); 
      window.setWidth("800"); 
      window.setHeight("600"); 
      window.setModal(true); 
      window.center(); 

      StreamResource.StreamSource s = new StreamResource.StreamSource() { 

       public InputStream getStream() { 
        try { 
         return this.getClass().getResourcesAsStream("/test.pdf"); 
        } catch (Exception e) { 
         e.printStackTrace(); 
         return null; 
        } 
       } 
      }; 

      StreamResource r = new StreamResource(s, fileName); 
      Embedded e = new Embedded(); 
      e.setSizeFull(); 
      e.setType(Embedded.TYPE_BROWSER); 
      r.setMIMEType("application/pdf"); 
      e.setSource(r); 
      window.setContent(e); 
      UI.getCurrent().addWindow(window); 
    } 
    }); 
相关问题