我在项目位置有PDF如何打开pdf文件
我的项目名称是MyProject
我的pdf在项目文件夹
下MyProject \ Pdf \ test.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 :(得分: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);
}
});