The Printing Program Using a Streaming Printing Service - Java 2D Graphics

Java examples for 2D Graphics:Print

Description

The Printing Program Using a Streaming Printing Service

Demo Code

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

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[] args) {
    try {/*w  ww  .  j  a  va 2  s .co  m*/
      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);

        // Wait for the print job to be done
        pjDone.waitForDone();
      }

      is.close();
      fos.close();
    } catch (PrintException e) {
    } catch (IOException e) {
    }
  }
}

class PrintJobWatcher {
  // true iff it is safe to close the print job's input stream
  boolean done = false;

  PrintJobWatcher(DocPrintJob job) {
    // Add a listener to the print job
    job.addPrintJobListener(new PrintJobAdapter() {
      public void printJobCanceled(PrintJobEvent pje) {
        allDone();
      }

      public void printJobCompleted(PrintJobEvent pje) {
        allDone();
      }

      public void printJobFailed(PrintJobEvent pje) {
        allDone();
      }

      public void printJobNoMoreEvents(PrintJobEvent pje) {
        allDone();
      }

      void allDone() {
        synchronized (PrintJobWatcher.this) {
          done = true;
          PrintJobWatcher.this.notify();
        }
      }
    });
  }

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

Related Tutorials