在gef中关于打印的功能,采用PrintGraphicalViewerOperation实现打印Ifile的功能。如果非特性的打印动作,可以采用gef中相关的PrintActioni类实现打印的工作。
相关的PrintAction类源代码在org.eclipse.gef.ui.actions.PrintAction;
在源代码:public class PrintFigureOperation extends PrintOperation ;
实现打印实质是一种的绘制页面的过程。代码如下:其他忽略;
/**
* Prints the pages based on the current print mode.
* @see org.eclipse.draw2d.PrintOperation#printPages()
*/
protected void printPages() {
Graphics graphics = getFreshPrinterGraphics();
IFigure figure = getPrintSource();
setupPrinterGraphicsFor(graphics, figure);
Rectangle bounds = figure.getBounds();
int x = bounds.x, y = bounds.y;
Rectangle clipRect = new Rectangle();
while (y < bounds.y + bounds.height) {
while (x < bounds.x + bounds.width) {
graphics.pushState();
getPrinter().startPage();
graphics.translate(-x, -y);
graphics.getClip(clipRect);
clipRect.setLocation(x, y);
graphics.clipRect(clipRect);
figure.paint(graphics);
getPrinter().endPage();
graphics.popState();
x += clipRect.width;
}
x = bounds.x;
y += clipRect.height;
}
}
在打印时必须注意的重点代码如下:
publicvoid run(IAction action) {
int style = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().getStyle();
Shell shell = new Shell((style & SWT.MIRRORED) != 0 ? SWT.RIGHT_TO_LEFT : SWT.NONE);
//构建当前的视图编辑器对象
GraphicalViewer viewer = new ScrollingGraphicalViewer();
viewer.createControl(shell);
viewer.setEditDomain(new DefaultEditDomain(null));
viewer.setRootEditPart(new ScalableFreeformRootEditPart());
viewer.setEditPartFactory(new GraphicalPartFactory());
//设置编辑的内容
viewer.setContents(getContents());
viewer.flush();
//设置打印的模式
int printMode =PrintFigureOperation.FIT_PAGE;
//调用自定义的代码对话框
if (printMode == -1)
return;
//开始执行打印操作
PrintDialog dialog = new PrintDialog(shell, SWT.NULL);
PrinterData data = dialog.open();
if (data != null) {
//gef中打印的操作
PrintGraphicalViewerOperation op =new PrintGraphicalViewerOperation(new Printer(data), viewer);
//设置答应的模式
op.setPrintMode(printMode);
//运行打印的文件
op.run(selectedFile.getName());
}
}