smartGWT的Canvas提供了两个方法分别用来对传入的Object或者Canvas组件直接打印和显示打印预览。
printComponents
public static void printComponents(Object[] components)
Generate printable HTML for the designated components and trigger the native print dialog, without ever showing the printable HTML to the user.
Parameters:
components - components to get the print HTML for. May also include raw HTML strings which will be folded into the generated print output
showPrintPreview
public static void showPrintPreview(Object[] components)
Show a Print containing a printable view of the components passed in.
Parameters:
components - components to get the print HTML for. May also include raw HTML strings which will be folded into the generated print output
表格必然有分页,打印的时候要打印所有的数据,因此必然需要使用相同的DataSource重新取一遍数据,而且这次要取所有数据;
含有所有数据的表格只用于打印,不用来显示(比如用户设定了每页显示10行数据,他不会希望点一下打印之后,表格显示了所有数据);
表格所在的页面可能有一些不需要打印的UI组件(通常只需要打印表格ListGrid)。
综合上述理由,有必要创建一个新的ListGrid,专门用于打印,打印之后即destroy()掉。
如果可以直接拷贝一份原来的ListGrid对象,然后对这份拷贝进行重新取数据等操作,就会十分完美,可惜Java对于对象的拷贝是相当麻烦的(对象要实现Cloneable接口等等)。
在下面的代码中,XXXGridView是需要被打印的UI组件,先创建一个它的实例,然后remove掉不需要被打印的member,加入两个button,分别为打印和取消。通过自定义的createDataSource()创建一个XXXGridDataSource的实例,把fetch到的data设到XXXGridView的ListGrid里面。然后调用printView.show()显示打印预览。
如果用户点打印,则调用Canvas.printComponents(new Object[]{printView}); 打印。
无论用户点击打印还是取消,都destroy掉这个XXXGridView的实例。
gridDisplay.getExportForm().getField(ExportForm.PRINT).addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
printView = new XXXGridView();
printView.removeMember(printView.getExportForm());
printView.removeMember(printView.getPageNavigationForm());
DynamicForm buttonForm = new DynamicForm();
ButtonItem printButton = new ButtonItem("print", "Print");
printButton.setEndRow(false);
printButton.setAlign(Alignment.CENTER);
printButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
Canvas.printComponents(new Object[]{printView});
printView.destroy();
}
});
ButtonItem cancelButton = new ButtonItem("cancel", "Cancel");
cancelButton.setStartRow(false);
cancelButton.setAlign(Alignment.CENTER);
cancelButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
printView.destroy();
}
});
buttonForm.setFields(printButton, cancelButton);
buttonForm.setNumCols(4);
buttonForm.setTitleSuffix(null);
buttonForm.setWidth100();
printView.addMember(buttonForm, 0);
XXXGridDataSource dataSource = createDataSource();
printView.setDatasource(dataSource);
dataSource.fetchData(new Criteria(), new DSCallback() {
@Override
public void execute(DSResponse response, Object rawData, DSRequest request) {
printView.getDataGrid().setData(response.getData());
printView.setHeight100();
printView.show();
}
});
}
});