Using a Streaming Printing Service : Print Service « 2D Graphics « Java Tutorial






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.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
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[] args) throws Exception{
    InputStream is = new BufferedInputStream(new FileInputStream("filename.gif"));

    OutputStream fos = new BufferedOutputStream(new FileOutputStream("filename.ps"));

    DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;
    StreamPrintServiceFactory[] factories = StreamPrintServiceFactory
        .lookupStreamPrintServiceFactories(flavor, DocFlavor.BYTE_ARRAY.POSTSCRIPT.getMimeType());

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

      PrintJobWatcher pjDone = new PrintJobWatcher(job);

      job.print(doc, null);

      pjDone.waitForDone();
    }

    is.close();
    fos.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) {
    }
  }
}








16.51.Print Service
16.51.1.List Print Services
16.51.2.Using a Printing Service
16.51.3.Using a Streaming Printing Service
16.51.4.Discovering Available Print Services
16.51.5.Discovering Available Streaming Print Services
16.51.6.Use a factory to create a print service
16.51.7.Listening for Print Service Status Changes
16.51.8.Listening for Print Job Status Changes
16.51.9.Determining the Capabilities of a Print Service
16.51.10.Determining Print Job Capabilities Supported by a Print Service