Java 如何使用vaadin代码打开项目文件夹中的pdf文件?
我有一个PDF在项目位置如何打开PDF文件 我的项目名是MyProject 我的pdf在项目文件夹下 MyProject\Pdf\test.Pdf如何打开我的Pdf文件 我需要在项目位置打开pdf文件 我试过下面的代码Java 如何使用vaadin代码打开项目文件夹中的pdf文件?,java,vaadin7,Java,Vaadin7,我有一个PDF在项目位置如何打开PDF文件 我的项目名是MyProject 我的pdf在项目文件夹下 MyProject\Pdf\test.Pdf如何打开我的Pdf文件 我需要在项目位置打开pdf文件 我试过下面的代码 final Button viewBtn= new Button("View Policy Schedule"); viewBtn.addClickListener( newButton.ClickListener()
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);
}
});
它不工作我有一个文件找不到异常移动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);
}
});