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

Java examples for 2D Graphics:Print

Description

The Printing Program Using a Printing Service

Demo Code

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;

public class Main {
  public static void main(String[] args) {
    try {//from  ww  w .jav a 2 s.  co m
      // Open the image file
      InputStream is = new BufferedInputStream(new FileInputStream(
          "filename.gif"));

      // Find the default service
      DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;
      PrintService service = PrintServiceLookup.lookupDefaultPrintService();

      // Create the print job
      DocPrintJob job = service.createPrintJob();
      Doc doc = new SimpleDoc(is, flavor, null);

      // Monitor print job events; for the implementation of PrintJobWatcher,
      // see Determining When a Print Job Has Finished
      PrintJobWatcher pjDone = new PrintJobWatcher(job);

      // Print it
      job.print(doc, null);

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

      // It is now safe to close the input stream
      is.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