CancelablePrintJob: cancel() : CancelablePrintJob « javax.print « Java by API






CancelablePrintJob: cancel()

  
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.print.CancelablePrintJob;
import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.SimpleDoc;
import javax.print.StreamPrintService;
import javax.print.StreamPrintServiceFactory;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;

public class Main {
  public static void main(String[] argv) throws Exception {
    OutputStream fos = new BufferedOutputStream(new FileOutputStream("filename.ps"));
    DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;
    InputStream is = new BufferedInputStream(new FileInputStream("filename.gif"));
    StreamPrintServiceFactory[] factories = StreamPrintServiceFactory
        .lookupStreamPrintServiceFactories(flavor, DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType());

    StreamPrintService service = factories[0].getPrintService(fos);
    final DocPrintJob job = service.createPrintJob();
    Doc doc = new SimpleDoc(is, flavor, null);

    PrintJobWatcher pjDone = new PrintJobWatcher(job);

    if (job instanceof CancelablePrintJob) {
      CancelablePrintJob cancelJob = (CancelablePrintJob) job;
      try {
        cancelJob.cancel();
      } catch (PrintException e) {
      }
    }
    job.print(doc, null);
    pjDone.waitForDone();
    is.close();
  }
}

class PrintJobWatcher {
  boolean done = false;

  PrintJobWatcher(DocPrintJob job) {
    job.addPrintJobListener(new PrintJobAdapter() {
      public void printJobCanceled(PrintJobEvent pje) {
        synchronized (PrintJobWatcher.this) {
          done = true;
          PrintJobWatcher.this.notify();
        }
      }

      public void printJobCompleted(PrintJobEvent pje) {
        synchronized (PrintJobWatcher.this) {
          done = true;
          PrintJobWatcher.this.notify();
        }
      }

      public void printJobFailed(PrintJobEvent pje) {
        synchronized (PrintJobWatcher.this) {
          done = true;
          PrintJobWatcher.this.notify();
        }
      }

      public void printJobNoMoreEvents(PrintJobEvent pje) {
        synchronized (PrintJobWatcher.this) {
          done = true;
          PrintJobWatcher.this.notify();
        }
      }
    });
  }

  public synchronized void waitForDone() {
    try {
      while (!done) {
        wait();
      }
    } catch (InterruptedException e) {
    }
  }
}

   
    
  








Related examples in the same category