コード例 #1
1
        public Print2DPrinterJob() {

                /* Construct the print request specification.
                * The print data is a Printable object.
                * the request additonally specifies a job name, 2 copies, and
                * landscape orientation of the media.
                */
                PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
                aset.add(OrientationRequested.LANDSCAPE);
                aset.add(new Copies(2));
                aset.add(new JobName("My job", null));

                /* Create a print job */
                PrinterJob pj = PrinterJob.getPrinterJob();       
                pj.setPrintable(this);
                /* locate a print service that can handle the request */
                PrintService[] services =
                        PrinterJob.lookupPrintServices();

                if (services.length > 0) {
                        System.out.println("selected printer " + services[0].getName());
                        try {
                                pj.setPrintService(services[0]);
                                pj.pageDialog(aset);
                                if(pj.printDialog(aset)) {
                                        pj.print(aset);
                                }
                        } catch (PrinterException pe) { 
                                System.err.println(pe);
                        }
                }
        }
コード例 #2
0
ファイル: Utilitaires.java プロジェクト: bianconejo/CEFX
  public static void exporterPapier(JasperPrint jPrint, Integer nbCopies) {

    // choix de l'imprimante par défaut
    PrintService service = PrintServiceLookup.lookupDefaultPrintService();

    // paramètres d'impression
    PrintRequestAttributeSet printRequestAttributeSetImpression =
        new HashPrintRequestAttributeSet();
    printRequestAttributeSetImpression.add(MediaSizeName.ISO_A4);
    printRequestAttributeSetImpression.add(new Copies(nbCopies));

    // paramètres de l'imprimante
    PrintServiceAttributeSet printServiceAttributeSetImpression =
        new HashPrintServiceAttributeSet();
    printServiceAttributeSetImpression.add(new PrinterName(service.getName(), null));

    // création de l'interface d'impression
    JRPrintServiceExporter imprimanteFacture = new JRPrintServiceExporter();

    // initialisation de l'interface d'impression
    imprimanteFacture.setParameter(JRExporterParameter.JASPER_PRINT, jPrint);
    imprimanteFacture.setParameter(
        JRPrintServiceExporterParameter.PRINT_REQUEST_ATTRIBUTE_SET,
        printRequestAttributeSetImpression);
    imprimanteFacture.setParameter(
        JRPrintServiceExporterParameter.PRINT_SERVICE_ATTRIBUTE_SET,
        printServiceAttributeSetImpression);

    try {
      imprimanteFacture.exportReport();
    } catch (Exception e) {
      throw new RuntimeException("Impossible de générer la Facture", e);
      //  COMMANDE ENREGISTREE MAIS NON IMPRIMEE
    }
  }
コード例 #3
0
  public PrintService[] getPrintServices(DocFlavor flavor, AttributeSet attributes) {

    SecurityManager security = System.getSecurityManager();
    if (security != null) {
      security.checkPrintJobAccess();
    }
    PrintRequestAttributeSet requestSet = null;
    PrintServiceAttributeSet serviceSet = null;

    if (attributes != null && !attributes.isEmpty()) {

      requestSet = new HashPrintRequestAttributeSet();
      serviceSet = new HashPrintServiceAttributeSet();

      Attribute[] attrs = attributes.toArray();
      for (int i = 0; i < attrs.length; i++) {
        if (attrs[i] instanceof PrintRequestAttribute) {
          requestSet.add(attrs[i]);
        } else if (attrs[i] instanceof PrintServiceAttribute) {
          serviceSet.add(attrs[i]);
        }
      }
    }

    /*
     * Special case: If client is asking for a particular printer
     * (by name) then we can save time by getting just that service
     * to check against the rest of the specified attributes.
     */
    PrintService[] services = null;
    if (serviceSet != null && serviceSet.get(PrinterName.class) != null) {
      PrinterName name = (PrinterName) serviceSet.get(PrinterName.class);
      PrintService service = getPrintServiceByName(name.getValue());
      if (service == null || !matchingService(service, serviceSet)) {
        services = new PrintService[0];
      } else {
        services = new PrintService[1];
        services[0] = service;
      }
    } else {
      services = getPrintServices();
    }

    if (services.length == 0) {
      return services;
    } else {
      ArrayList matchingServices = new ArrayList();
      for (int i = 0; i < services.length; i++) {
        try {
          if (services[i].getUnsupportedAttributes(flavor, requestSet) == null) {
            matchingServices.add(services[i]);
          }
        } catch (IllegalArgumentException e) {
        }
      }
      services = new PrintService[matchingServices.size()];
      return (PrintService[]) matchingServices.toArray(services);
    }
  }
コード例 #4
0
ファイル: PrintTools.java プロジェクト: MigthyThor/FidoCadJ
  /**
   * Show a dialog for printing the current drawing.
   *
   * @param fff the parent frame which will be used for dialogs and message boxes.
   * @param CCr the CircuitPanel containing the drawing to be exported.
   */
  public void printDrawing(JFrame fff, CircuitPanel CCr) {
    cc = CCr;
    DialogPrint dp = new DialogPrint(fff);
    dp.setMirror(printMirror);
    dp.setFit(printFitToPage);
    dp.setBW(printBlackWhite);
    dp.setLandscape(printLandscape);
    dp.setVisible(true);

    // Get some information about the printing options.
    printMirror = dp.getMirror();
    printFitToPage = dp.getFit();
    printLandscape = dp.getLandscape();
    printBlackWhite = dp.getBW();

    Vector<LayerDesc> ol = cc.dmp.getLayers();
    if (dp.shouldPrint()) {
      if (printBlackWhite) {
        Vector<LayerDesc> v = new Vector<LayerDesc>();

        // Here we create an alternative array of layers in
        // which all colors are pitch black. This may be
        // useful for PCB's.

        for (int i = 0; i < LayerDesc.MAX_LAYERS; ++i)
          v.add(
              new LayerDesc(
                  new ColorSwing(Color.black),
                  ((LayerDesc) ol.get(i)).getVisible(),
                  "B/W",
                  ((LayerDesc) ol.get(i)).getAlpha()));
        cc.dmp.setLayers(v);
      }
      PrinterJob job = PrinterJob.getPrinterJob();
      job.setPrintable(this);
      boolean ok = job.printDialog();
      if (ok) {
        try {
          PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
          // Set the correct printing orientation.
          if (printLandscape) {
            aset.add(OrientationRequested.LANDSCAPE);
          } else {
            aset.add(OrientationRequested.PORTRAIT);
          }
          job.print(aset);
        } catch (PrinterException ex) {
          // The job did not successfully complete
          JOptionPane.showMessageDialog(fff, Globals.messages.getString("Print_uncomplete"));
        }
      }
      cc.dmp.setLayers(ol);
    }
  }
コード例 #5
0
  private void defaultPrintPage(InvoicePagePrint pageprintdocumnet) {
    PrintService[] service = PrinterJob.lookupPrintServices(); // list
    // of
    // printers
    int count = service.length;
    PrintService printSvc = null;
    for (int i = 0; i < count; i++) {
      System.out.println("Service name: " + service[i].getName());
      if (service[i].getName().indexOf("PDFcamp") != -1) {
        printSvc = service[i];
        i = count;
      }
    }

    //  TSP650
    PageFormat format = new PageFormat();
    Paper paper = new Paper();

    double paperWidth = 3.25;
    double paperHeight = 11.69;
    double leftMargin = 0.19;
    double rightMargin = 0.25;
    double topMargin = 0;
    double bottomMargin = 0.01;

    paper.setSize(paperWidth * 72.0, paperHeight * 72.0);
    paper.setImageableArea(
        leftMargin * 72.0,
        topMargin * 72.0,
        (paperWidth - leftMargin - rightMargin) * 72.0,
        (paperHeight - topMargin - bottomMargin) * 72.0);

    format.setPaper(paper);

    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
    aset.add(OrientationRequested.PORTRAIT);

    PrinterJob printerJob = PrinterJob.getPrinterJob();
    try {
      printerJob.setPrintService(printSvc);
    } catch (PrinterException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    // Printable printable = new ReceiptPrintTest();
    format = printerJob.validatePage(format);
    // printerJob.setPrintable(printable, format);
    printerJob.setPrintable(pageprintdocumnet, format);
    try {
      printerJob.print(aset);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #6
0
 /**
  * For any given paper, this retrieves the hardware margins, or a reasonable and safe guess if
  * they aren't available.
  */
 public Rectangle2D printableArea(Paper paper) {
   int INCH = MediaSize.INCH;
   Rectangle2D area = null;
   MediaSizeName msn =
       MediaSize.findMedia(
           (float) paper.getWidth(), (float) paper.getHeight(), (int) (INCH / 72.0));
   if (msn != null) {
     PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
     pras.add(msn);
     MediaPrintableArea[] mpa =
         (MediaPrintableArea[])
             service.getSupportedAttributeValues(MediaPrintableArea.class, null, pras);
     if (mpa != null && mpa.length > 0) {
       int MPA_INCH = MediaPrintableArea.INCH;
       area =
           new Rectangle2D(
               mpa[0].getX(MPA_INCH),
               mpa[0].getY(MPA_INCH),
               mpa[0].getWidth(MPA_INCH),
               mpa[0].getHeight(MPA_INCH));
     }
   }
   // If we could not get the area for whatever reason,
   // then go with 0.75" margins unless they are too large
   // ie its a really small paper.
   if (area == null) {
     double pw = (paper.getWidth() / 72.0);
     ;
     double ph = (paper.getHeight() / 72.0);
     double iw, ih;
     if (pw < 3.0) {
       iw = 0.75 * pw;
     } else {
       iw = pw - 1.5;
     }
     if (ph < 3.0) {
       ih = 0.75 * ph;
     } else {
       ih = ph - 1.5;
     }
     double lm = (pw - iw) / 2.0;
     double tm = (ph - ih) / 2.0;
     area = new Rectangle2D(lm, tm, iw, ih);
   }
   return area;
 }
コード例 #7
0
ファイル: PreviewPanel.java プロジェクト: chochreiner/jabref
    @Override
    public void actionPerformed(ActionEvent arg0) {

      // Background this, as it takes a while.
      JabRefExecutorService.INSTANCE.execute(
          () -> {
            try {
              PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
              pras.add(new JobName(entry.map(BibEntry::getCiteKey).orElse("NO ENTRY"), null));
              previewPane.print(null, null, true, null, pras, false);

            } catch (PrinterException e) {
              // Inform the user... we don't know what to do.
              JOptionPane.showMessageDialog(
                  PreviewPanel.this,
                  Localization.lang("Could not print preview") + ".\n" + e.getMessage(),
                  Localization.lang("Print entry preview"),
                  JOptionPane.ERROR_MESSAGE);
              LOGGER.info("Could not print preview", e);
            }
          });
    }
コード例 #8
0
  private void print() {
    desktop.setWaitCursor();
    hideCatchingRooms();
    printDlg.setVisible(true);
    try {
      List<Module> modules =
          memberService.findModuleOrders(personFile.getId(), dates.getStart(), dates.getEnd());
      StringBuilder sb = new StringBuilder(personFile.getContact().getFirstnameName());

      if (modules != null && !modules.isEmpty()) {
        sb.append(" : ");
        sb.append(modules.get(0).getTitle());
        if (modules.size() > 1) {
          sb.append("..."); // do not display next modules
        }
      }

      MessageFormat header = new MessageFormat(sb.toString());
      MessageFormat footer = new MessageFormat("Page {0}");
      PrintRequestAttributeSet prs = new HashPrintRequestAttributeSet();
      prs.add(MediaSizeName.ISO_A4);
      prs.add(Sides.TWO_SIDED_LONG_EDGE);
      prs.add(OrientationRequested.PORTRAIT);
      prs.add(
          new JobName(
              BundleUtil.getLabel("Follow.up.label") + "-" + personFile.getId(),
              Locale.getDefault()));
      // 210 x 297 mm | 8.3 x 11.7 in 1 inch = 25.4 mm

      MediaPrintableArea printableArea =
          new MediaPrintableArea(10f, 10f, 190f, 277f, MediaPrintableArea.MM);
      prs.add(printableArea);
      printTable.print(JTable.PrintMode.FIT_WIDTH, header, footer, true, prs, true);
    } catch (PrinterException ex) {
      GemLogger.logException(ex);
    } finally {
      printDlg.setVisible(false);
      desktop.setDefaultCursor();
    }
  }
コード例 #9
0
ファイル: TiledPrintingAWTBase.java プロジェクト: metsci/jogl
  /**
   * @param cont
   * @param pOrientation
   * @param paper
   * @param offscrnImageType if < 0 onscreen, otherwise integer BufferedImage type
   * @param dpi
   * @param numSamples multisampling value: < 0 turns off, == 0 leaves as-is, > 0 enables using
   *     given num samples
   * @param tileWidth custom tile width for {@link TileRenderer#setTileSize(int, int, int) tile
   *     renderer}, pass -1 for default.
   * @param tileHeight custom tile height for {@link TileRenderer#setTileSize(int, int, int) tile
   *     renderer}, pass -1 for default.
   * @param resizeWithinPrintTest TODO
   */
  public PrintableBase doPrintAuto(
      Container cont,
      int pOrientation,
      Paper paper,
      int offscrnImageType,
      int dpi,
      int numSamples,
      int tileWidth,
      int tileHeight,
      boolean resizeWithinPrintTest) {
    lock.lock();
    try {
      final PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
      aset.add(MediaSizeName.ISO_A1); // 594 × 841 mm
      aset.add(MediaSizeName.ISO_A2); // 420 × 594 mm
      aset.add(MediaSizeName.ISO_A3); // 297 × 420 mm
      aset.add(MediaSizeName.ISO_A4); // 210 × 297 mm

      printCount++;

      final String psMimeType = "application/postscript";
      final String pdfMimeType = "application/pdf";
      final PrinterJob pj = PrinterJob.getPrinterJob();

      StreamPrintServiceFactory[] factories = PrinterJob.lookupStreamPrintServices(pdfMimeType);
      if (factories.length > 0) {
        final String fname =
            getPrintFilename(
                offscrnImageType,
                dpi,
                numSamples,
                tileWidth,
                tileHeight,
                "pdf",
                resizeWithinPrintTest);
        System.err.println("doPrint: dpi " + dpi + ", " + fname);
        FileOutputStream outstream;
        try {
          outstream = new FileOutputStream(fname);
          return doPrintAutoImpl(
              cont,
              pj,
              factories[0].getPrintService(outstream),
              pOrientation,
              paper,
              offscrnImageType,
              dpi,
              numSamples,
              tileWidth,
              tileHeight,
              resizeWithinPrintTest);
        } catch (FileNotFoundException e) {
          Assert.assertNull("Unexpected exception", e);
        }
      }
      System.err.println("No PDF");

      factories = PrinterJob.lookupStreamPrintServices(psMimeType);
      if (factories.length > 0) {
        final String fname =
            getPrintFilename(
                offscrnImageType,
                dpi,
                numSamples,
                tileWidth,
                tileHeight,
                "ps",
                resizeWithinPrintTest);
        System.err.println("doPrint: dpi " + dpi + ", " + fname);
        FileOutputStream outstream;
        try {
          outstream = new FileOutputStream(fname);
          return doPrintAutoImpl(
              cont,
              pj,
              factories[0].getPrintService(outstream),
              pOrientation,
              paper,
              offscrnImageType,
              dpi,
              numSamples,
              tileWidth,
              tileHeight,
              resizeWithinPrintTest);
        } catch (FileNotFoundException e) {
          Assert.assertNull("Unexpected exception", e);
        }
      }
      System.err.println("No PS");
      return null;
    } finally {
      lock.unlock();
    }
  }
コード例 #10
0
    public void printPage(String size) {
      double width = 0.0;
      double height = 0.0;
      double margin = 0.0;
      PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
      try {
        PrinterJob pj = PrinterJob.getPrinterJob();
        if (pj.printDialog()) {
          PageFormat pf = pj.defaultPage();
          Paper paper = pf.getPaper();
          if (size.equals("3r")) {
            width = 5d * 72d;
            height = 3.5d * 72d;
            margin = 0d * 72d;
            aset.add(MediaSizeName.JIS_B7);
          } else if (size.equals("4r")) {
            width = 6d * 72d;
            height = 4d * 72d;
            margin = 0d * 72d;
            aset.add(MediaSizeName.JAPANESE_POSTCARD);
          } else if (size.equals("5r")) {
            width = 7d * 72d;
            height = 5d * 72d;
            margin = 0d * 72d;
            aset.add(MediaSizeName.NA_5X7);
          } else if (size.equals("6r")) {
            width = 8d * 72d;
            height = 6d * 72d;
            margin = 0d * 72d;
            aset.add(MediaSizeName.JAPANESE_DOUBLE_POSTCARD);
          } else if (size.equals("8r")) {
            width = 10d * 72d;
            height = 8d * 72d;
            margin = 0d * 72d;
            aset.add(MediaSizeName.NA_8X10);
          }
          paper.setSize(width, height);
          paper.setImageableArea(margin, margin, width - (margin * 2), height - (margin * 2));
          System.out.println("Before- " + dump(paper));
          pf.setOrientation(PageFormat.LANDSCAPE);
          pf.setPaper(paper);
          System.out.println("After- " + dump(paper));
          System.out.println("After- " + dump(pf));
          dump(pf);
          PageFormat validatePage = pj.validatePage(pf);
          System.out.println("Valid- " + dump(validatePage));

          Book pBook = new Book();
          pBook.append(this, pf);
          pj.setPageable(pBook);

          aset.add(OrientationRequested.LANDSCAPE);

          try {
            pj.setPrintable(this);
            pj.print(aset);
          } catch (PrinterException ex) {
            ex.printStackTrace();
          }
        }

      } catch (Exception exp) {
        exp.printStackTrace();
      }
    }
コード例 #11
0
  private void getAttributeValues(DocFlavor flavor) throws PrintException {

    if (reqAttrSet.get(Fidelity.class) == Fidelity.FIDELITY_TRUE) {
      fidelity = true;
    } else {
      fidelity = false;
    }

    Class category;
    Attribute[] attrs = reqAttrSet.toArray();
    for (int i = 0; i < attrs.length; i++) {
      Attribute attr = attrs[i];
      category = attr.getCategory();
      if (fidelity == true) {
        if (!service.isAttributeCategorySupported(category)) {
          notifyEvent(PrintJobEvent.JOB_FAILED);
          throw new PrintJobAttributeException("unsupported category: " + category, category, null);
        } else if (!service.isAttributeValueSupported(attr, flavor, null)) {
          notifyEvent(PrintJobEvent.JOB_FAILED);
          throw new PrintJobAttributeException("unsupported attribute: " + attr, null, attr);
        }
      }
      if (category == Destination.class) {
        URI uri = ((Destination) attr).getURI();
        if (!"file".equals(uri.getScheme())) {
          notifyEvent(PrintJobEvent.JOB_FAILED);
          throw new PrintException("Not a file: URI");
        } else {
          try {
            mDestination = (new File(uri)).getPath();
          } catch (Exception e) {
            throw new PrintException(e);
          }
          // check write access
          SecurityManager security = System.getSecurityManager();
          if (security != null) {
            try {
              security.checkWrite(mDestination);
            } catch (SecurityException se) {
              notifyEvent(PrintJobEvent.JOB_FAILED);
              throw new PrintException(se);
            }
          }
        }
      } else if (category == JobName.class) {
        jobName = ((JobName) attr).getValue();
      } else if (category == Copies.class) {
        copies = ((Copies) attr).getValue();
      } else if (category == Media.class) {
        if (attr instanceof MediaSizeName) {
          mediaName = (MediaSizeName) attr;
          // If requested MediaSizeName is not supported,
          // get the corresponding media size - this will
          // be used to create a new PageFormat.
          if (!service.isAttributeValueSupported(attr, null, null)) {
            mediaSize = MediaSize.getMediaSizeForName(mediaName);
          }
        }
      } else if (category == OrientationRequested.class) {
        orient = (OrientationRequested) attr;
      }
    }
  }
コード例 #12
0
  /* There's some inefficiency here as the job set is created even though
   * it may never be requested.
   */
  private synchronized void initializeAttributeSets(Doc doc, PrintRequestAttributeSet reqSet) {

    reqAttrSet = new HashPrintRequestAttributeSet();
    jobAttrSet = new HashPrintJobAttributeSet();

    Attribute[] attrs;
    if (reqSet != null) {
      reqAttrSet.addAll(reqSet);
      attrs = reqSet.toArray();
      for (int i = 0; i < attrs.length; i++) {
        if (attrs[i] instanceof PrintJobAttribute) {
          jobAttrSet.add(attrs[i]);
        }
      }
    }

    DocAttributeSet docSet = doc.getAttributes();
    if (docSet != null) {
      attrs = docSet.toArray();
      for (int i = 0; i < attrs.length; i++) {
        if (attrs[i] instanceof PrintRequestAttribute) {
          reqAttrSet.add(attrs[i]);
        }
        if (attrs[i] instanceof PrintJobAttribute) {
          jobAttrSet.add(attrs[i]);
        }
      }
    }

    /* add the user name to the job */
    String userName = "";
    try {
      userName = System.getProperty("user.name");
    } catch (SecurityException se) {
    }

    if (userName == null || userName.equals("")) {
      RequestingUserName ruName = (RequestingUserName) reqSet.get(RequestingUserName.class);
      if (ruName != null) {
        jobAttrSet.add(new JobOriginatingUserName(ruName.getValue(), ruName.getLocale()));
      } else {
        jobAttrSet.add(new JobOriginatingUserName("", null));
      }
    } else {
      jobAttrSet.add(new JobOriginatingUserName(userName, null));
    }

    /* if no job name supplied use doc name (if supplied), if none and
     * its a URL use that, else finally anything .. */
    if (jobAttrSet.get(JobName.class) == null) {
      JobName jobName;
      if (docSet != null && docSet.get(DocumentName.class) != null) {
        DocumentName docName = (DocumentName) docSet.get(DocumentName.class);
        jobName = new JobName(docName.getValue(), docName.getLocale());
        jobAttrSet.add(jobName);
      } else {
        String str = "JPS Job:" + doc;
        try {
          Object printData = doc.getPrintData();
          if (printData instanceof URL) {
            str = ((URL) (doc.getPrintData())).toString();
          }
        } catch (IOException e) {
        }
        jobName = new JobName(str, null);
        jobAttrSet.add(jobName);
      }
    }

    jobAttrSet = AttributeSetUtilities.unmodifiableView(jobAttrSet);
  }
コード例 #13
0
  /**
   * Presents a dialog to the user for selecting a print service (printer). It is displayed at the
   * location specified by the application and is modal. If the specification is invalid or would
   * make the dialog not visible it will be displayed at a location determined by the
   * implementation. The dialog blocks its calling thread and is application modal.
   *
   * <p>The dialog may include a tab panel with custom UI lazily obtained from the PrintService's
   * ServiceUIFactory when the PrintService is browsed. The dialog will attempt to locate a
   * MAIN_UIROLE first as a JComponent, then as a Panel. If there is no ServiceUIFactory or no
   * matching role the custom tab will be empty or not visible.
   *
   * <p>The dialog returns the print service selected by the user if the user OK's the dialog and
   * null if the user cancels the dialog.
   *
   * <p>An application must pass in an array of print services to browse. The array must be non-null
   * and non-empty. Typically an application will pass in only PrintServices capable of printing a
   * particular document flavor.
   *
   * <p>An application may pass in a PrintService to be initially displayed. A non-null parameter
   * must be included in the array of browsable services. If this parameter is null a service is
   * chosen by the implementation.
   *
   * <p>An application may optionally pass in the flavor to be printed. If this is non-null choices
   * presented to the user can be better validated against those supported by the services. An
   * application must pass in a PrintRequestAttributeSet for returning user choices. On calling the
   * PrintRequestAttributeSet may be empty, or may contain application-specified values.
   *
   * <p>These are used to set the initial settings for the initially displayed print service. Values
   * which are not supported by the print service are ignored. As the user browses print services,
   * attributes and values are copied to the new display. If a user browses a print service which
   * does not support a particular attribute-value, the default for that service is used as the new
   * value to be copied.
   *
   * <p>If the user cancels the dialog, the returned attributes will not reflect any changes made by
   * the user.
   *
   * <p>A typical basic usage of this method may be :
   *
   * <pre>{@code
   * PrintService[] services = PrintServiceLookup.lookupPrintServices(
   *                            DocFlavor.INPUT_STREAM.JPEG, null);
   * PrintRequestAttributeSet attributes = new HashPrintRequestAttributeSet();
   * if (services.length > 0) {
   *    PrintService service =  ServiceUI.printDialog(null, 50, 50,
   *                                               services, services[0],
   *                                               null,
   *                                               attributes);
   *    if (service != null) {
   *     ... print ...
   *    }
   * }
   * }</pre>
   *
   * <p>
   *
   * @param gc used to select screen. null means primary or default screen.
   * @param x location of dialog including border in screen coordinates
   * @param y location of dialog including border in screen coordinates
   * @param services to be browsable, must be non-null.
   * @param defaultService - initial PrintService to display.
   * @param flavor - the flavor to be printed, or null.
   * @param attributes on input is the initial application supplied preferences. This cannot be null
   *     but may be empty. On output the attributes reflect changes made by the user.
   * @return print service selected by the user, or null if the user cancelled the dialog.
   * @throws HeadlessException if GraphicsEnvironment.isHeadless() returns true.
   * @throws IllegalArgumentException if services is null or empty, or attributes is null, or the
   *     initial PrintService is not in the list of browsable services.
   */
  public static PrintService printDialog(
      GraphicsConfiguration gc,
      int x,
      int y,
      PrintService[] services,
      PrintService defaultService,
      DocFlavor flavor,
      PrintRequestAttributeSet attributes)
      throws HeadlessException {
    int defaultIndex = -1;

    if (GraphicsEnvironment.isHeadless()) {
      throw new HeadlessException();
    } else if ((services == null) || (services.length == 0)) {
      throw new IllegalArgumentException("services must be non-null " + "and non-empty");
    } else if (attributes == null) {
      throw new IllegalArgumentException("attributes must be non-null");
    }

    if (defaultService != null) {
      for (int i = 0; i < services.length; i++) {
        if (services[i].equals(defaultService)) {
          defaultIndex = i;
          break;
        }
      }

      if (defaultIndex < 0) {
        throw new IllegalArgumentException("services must contain " + "defaultService");
      }
    } else {
      defaultIndex = 0;
    }

    // For now we set owner to null. In the future, it may be passed
    // as an argument.
    Window owner = null;

    Rectangle gcBounds =
        (gc == null)
            ? GraphicsEnvironment.getLocalGraphicsEnvironment()
                .getDefaultScreenDevice()
                .getDefaultConfiguration()
                .getBounds()
            : gc.getBounds();

    ServiceDialog dialog;
    if (owner instanceof Frame) {
      dialog =
          new ServiceDialog(
              gc,
              x + gcBounds.x,
              y + gcBounds.y,
              services,
              defaultIndex,
              flavor,
              attributes,
              (Frame) owner);
    } else {
      dialog =
          new ServiceDialog(
              gc,
              x + gcBounds.x,
              y + gcBounds.y,
              services,
              defaultIndex,
              flavor,
              attributes,
              (Dialog) owner);
    }
    Rectangle dlgBounds = dialog.getBounds();

    // get union of all GC bounds
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] gs = ge.getScreenDevices();
    for (int j = 0; j < gs.length; j++) {
      gcBounds = gcBounds.union(gs[j].getDefaultConfiguration().getBounds());
    }

    // if portion of dialog is not within the gc boundary
    if (!gcBounds.contains(dlgBounds)) {
      // put in the center relative to parent frame/dialog
      dialog.setLocationRelativeTo(owner);
    }
    dialog.show();

    if (dialog.getStatus() == ServiceDialog.APPROVE) {
      PrintRequestAttributeSet newas = dialog.getAttributes();
      Class dstCategory = Destination.class;
      Class amCategory = SunAlternateMedia.class;
      Class fdCategory = Fidelity.class;

      if (attributes.containsKey(dstCategory) && !newas.containsKey(dstCategory)) {
        attributes.remove(dstCategory);
      }

      if (attributes.containsKey(amCategory) && !newas.containsKey(amCategory)) {
        attributes.remove(amCategory);
      }

      attributes.addAll(newas);

      Fidelity fd = (Fidelity) attributes.get(fdCategory);
      if (fd != null) {
        if (fd == Fidelity.FIDELITY_TRUE) {
          removeUnsupportedAttributes(dialog.getPrintService(), flavor, attributes);
        }
      }
    }

    return dialog.getPrintService();
  }