import org.eclipse.swt.printing.Printer; //导入方法依赖的package包/类
/** {@inheritDoc} */
@Override
public void run()
{
// Get snapshot. Disposed at end of printing
final Image snapshot = media_pool.get(ImageConverter.convertToSWT(graph.getImage()));
if (snapshot == null)
{
Logger.getLogger(getClass().getName()).fine("Cannot obtain image");
return;
}
// Printer GUI
final PrintDialog dlg = new PrintDialog(shell);
PrinterData data = dlg.open();
if (data == null)
{
Logger.getLogger(getClass().getName()).fine("Cannot obtain printer");
snapshot.dispose();
return;
}
// At least on Linux, access to SWT Printer must be on UI thread.
// Printing in other thread can deadlock with UI thread.
final Printer printer = new Printer(data);
try
{
if (!printer.startJob("Data Browser"))
{
Logger.getLogger(getClass().getName()).fine("Cannot start print job");
return;
}
try
{ // Printer page info
final Rectangle area = printer.getClientArea();
final Rectangle trim = printer.computeTrim(0, 0, 0, 0);
final Point dpi = printer.getDPI();
// Compute layout
final Rectangle image_rect = snapshot.getBounds();
// Leave one inch on each border.
// (copied the computeTrim stuff from an SWT example.
// Really no clue...)
final int left_right = dpi.x + trim.x;
final int top_bottom = dpi.y + trim.y;
final int printed_width = area.width - 2*left_right;
// Try to scale height according to on-screen aspect ratio.
final int max_height = area.height - 2*top_bottom;
final int printed_height = Math.min(max_height,
image_rect.height * printed_width / image_rect.width);
// Print one page
printer.startPage();
final GC gc = new GC(printer);
gc.drawImage(snapshot, 0, 0, image_rect.width, image_rect.height,
left_right, top_bottom, printed_width, printed_height);
printer.endPage();
}
finally
{
printer.endJob();
}
}
finally
{
printer.dispose();
snapshot.dispose();
}
}