使用Vaadin从菜单栏打开pdf文件
我的vaadin应用程序中有一个菜单栏,想要添加一个项目以打开pdf文件是浏览器的新标签.我找到了一些使用按钮打开文件的解决方案,但是我必须使用MenuItem ...
I have a menubar in my vaadin application and want to add an item to open a pdf-file is a new tab of the browser. I found some solutions to open files with a button, but I have to use an MenuItem...
MenuBar.Command commandHandler = new MenuBar.Command() {
@Override
public void menuSelected(MenuItem selectedItem) {
if (selectedItem.equals(menu_help)) {
openHelp();
}
}
};
...
menu_help = menuBar
.addItem("", WebImageList.getImage(ImageList.gc_helpIcon),
commandHandler);
...
private void openHelp() {
// open pdf-file in new window
}
感谢帮助!
解决方案:
private void openHelp() {
final String basepath = VaadinService.getCurrent().getBaseDirectory().getAbsolutePath();
Resource pdf = new FileResource(new File(basepath + "/WEB-INF/datafiles/help.pdf"));
setResource("help", pdf);
ResourceReference rr = ResourceReference.create(pdf, this, "help");
Page.getCurrent().open(rr.getURL(), "blank_");
}
注意:此代码有效,但是代码的结构并不完美;-)最好将"basepath"和"pdf"存储为属性...
Attention: This code works, but the the structure of code is not perfect ;-) Better is to store "basepath" and "pdf" as attribute...
There is a similar problem described here: How to specify a button to open an URL? One possible solution:
public class MyMenuBar extends MenuBar {
ResourceReference rr;
public MyMenuBar() {
Resource pdf = new FileResource(new File("C:/temp/temp.pdf"));
setResource("help", pdf);
rr = ResourceReference.create(pdf, this, "help");
}
private void openHelp() {
Page.getCurrent().open(rr.getURL(), "blank_");
}
...
}
AbstractClientConnector的setResource方法受保护,因此这是您需要扩展一些Vaadin组件以使其起作用的方法.这就是为什么我在这里创建类MyMenuBar的原因.如果您使用的是外部资源,则无需使用setResource将其附加到任何组件,那么这不是必需的.
The setResource method of AbstractClientConnector is protected, so this is you need to extend some Vaadin component to make it work. This is why Im creating the class MyMenuBar here. If you are using an external resource you don't need to attach it to any component with setResource and then this is not nessecary.